【问题标题】:For Loop to print out 10 values by multiplyingFor循环通过乘法打印出10个值
【发布时间】:2014-10-13 03:33:06
【问题描述】:

我一直在寻找正确的循环来打印值,所以我认为 For 循环会更容易使用。我想打印 10 次值以及从 1000 到 10000 或 1 到 10 的计时器结果,无论你怎么称呼它。代码如下:

cout << " N Value | Array Sort Time | Listed List Sort Time" << endl;
cout << "               (seconds)           (seconds) " << endl;
cout << endl;

for(int x = 1; x <= 10; x++)
{

    x = x*n;
    printf(" %d", n);
    int m = n; //copy N value for new integer to do 2nd while loop

    begin = clock();
    while(n != 0)
    {
        input = rand()%n;

        addArray(input, pArray, size);
        n--;

        if( input == -1)
        {
            break;   // end of list, don't add it to list
        }
    }
    end = clock();
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("          %5.3f", time_spent);

    begin = clock();
    while(m != 0)
    {
        input = rand()%m;

        addNode(pHead, input);
        m--;

        // break if end of list
        if( input == -1)
        {
            break;   // end of list, don't add it to list
        }
    }
    end = clock();
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("               %5.3f", time_spent);
}

它只打印一次,所以我的愚蠢代码是怎么回事?!

【问题讨论】:

  • 什么只打印一次?
  • 我输入的第一个值。我希望它能用 x++ 打印出接下来的 9 个值。
  • 所以看起来你的 while 循环永远不会结束 - 在调试器中运行它或添加一些打印来跟踪正在发生的事情。
  • 多种可能性,请出示n, begin, end,input, time_spent的声明。显示n 的值。假设inputnintinput = rand()%n; ... if( input == -1) 永远不会是真的。

标签: c++ c for-loop printing timer


【解决方案1】:

您的打印语句不在循环中。

因此,它们每个只执行一次。

如果您希望在每次循环运行时打印它们,您的打印语句需要在循环中。

此外,如果您还没有将“n”变量初始化为大于 0 的值。

【讨论】:

    【解决方案2】:

    我想出了解决这个问题的方法。小错误!这是解决方案。

    for(int x = 1; x <= 10; x++)
    {
        n = 1000*x; //ta-da!!!!
        int m = n; //copy N value for new integer to do 2nd while loop
    ......
    }
    

    希望这在未来对其他程序员有用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      相关资源
      最近更新 更多