我正在为我的 C++ 课做作业。在这个作业中,我需要编写一个程序,它从 cin 读取数字然后对它们求和,当使用 while 循环输入 0 时停止。
我已经编写了代码并得到了我需要的结果。但是,我陷入了一个持续重新打印结果的 while 循环中。任何人都可以在打印一次结果后给我一些建议来结束这个循环吗?
这是我的代码:
int main ()
{
int i(1), sum(0);
int sum2(0);
const int max(10);
cout << "Enter numbers, one per line. Enter 0 to end:" << endl;
while (i!=0)
{
cin >> i;
sum += i; //add current value of i to sum
sum2 += 1;
}
while (i==0)
{
if (sum < 100) // If total is less than 100
cout << "Thank you. The total was " << sum << endl
<< "The total number of inputs reads: " << sum2 << endl
<< "The total is less than 100." << endl ;
else // Else total is greater than 100
cout << "Thank you. The total was " << sum << endl
<< "The total number of inputs reads: " << sum2 << endl
<< "The total is greater than 100." << endl ;
}
} //End of Int Main
希望结果没问题。抱歉,我不确定如何在每行上发布数字。我还尝试将 while (i==0) 更改为 if 语句 if (i==0) 但这会在输入 0 时关闭程序。有人有有用的建议吗?我会很感激。^_^
更新:对不起,我忘了提到我还必须包括一个跟踪输入数量的循环计数器,一个确定总值是否小于或大于 100 的注释,以及一个确定总输入数的语句输入。这就是最后的 if else 语句的原因。我尝试取出最后一个 while 语句,因为我知道这是无限循环的原因,但是当我这样做时它不会显示结果。我将代码更改为:
int main ()
{
int i(1), sum(0);
int sum2(0);
const int max(10);
cout << "Enter numbers, one per line. Enter 0 to end:" << endl;
while (i!=0)
{
cin >> i;
sum += i; //add current value of i to sum
sum2 += 1;
}
if (sum < 100) // If total is less than 100
cout << "Thank you. The total was " << sum << endl
<< "The total number of inputs reads: " << sum2 << endl
<< "The total is less than 100." << endl ;
else // Else total is greater than 100
cout << "Thank you. The total was " << sum << endl
<< "The total number of inputs reads: " << sum2 << endl
<< "The total is greater than 100." << endl ;
} //End of Int Main
我的输出应该是
Enter numbers, one per line. Enter 0 to end:
7
8
6
5
5
9
8
0
Thank you. The total was 48.
The total number of inputs read: 8
The total is less than 100.