【问题标题】:Cannot to print in for loop无法在for循环中打印
【发布时间】:2019-10-14 02:26:53
【问题描述】:

下面是我的代码:

#include <iostream>

using namespace std;

int main()
{
    int numboftimes, n, sumvalue = 0, strvalue = 0;

    cout << "Enter Number of Times You Want The Loop to Run: ";
    cin >> numboftimes;

    for (n = 1; n <= numboftimes; n++)
    {
        sumvalue += n;
        strvalue += 1; 
    }

    cout << "You ran the for loop: " << numboftimes << " times. \n";
}

我无法在 for 循环中获得 cout 来打印出迭代。即 1+2+3+4+5 = 15。

【问题讨论】:

  • 为什么不呢?当你尝试时会发生什么?请阅读How to Ask,然后阅读edit 您的问题并添加循环中打印的代码。

标签: c++ c++14


【解决方案1】:

您需要打印循环中的每个迭代:

for (n = 1; n <= numboftimes; n++) {
    sumvalue += n;
    strvalue += 1;
    cout << "This is the " << numboftimes << " iteration to print" << endl;
    cout << "The sum is " << sumvalue << endl;
}

通过这种方式,您可以打印每次迭代。

【讨论】:

    【解决方案2】:

    当您打印变量 numboftime 时,您只是在打印一个常量值

    for(int n=0; n < numboftimes ; n++)
         cout << n << endl;
    

    你把 cout 放在 for 循环之外,它只会输出一次,并且只输出整数次

    【讨论】:

    • 是的,抱歉,因为我是在手机上写的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 2022-01-23
    • 2021-09-24
    相关资源
    最近更新 更多