gpt4 book ai didi

c++ - 陷入 while 循环 c

转载 作者:行者123 更新时间:2023-11-30 02:01:03 28 4
gpt4 key购买 nike

我正在为我的 C++ 类(class)做作业。在这个作业中,我需要编写一个程序,从 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.

最佳答案

i 停留在 0 并且在您退出第一个循环后永远不会改变。不要使用另一个 while 循环,只需在之后打印结果即可。

关于c++ - 陷入 while 循环 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14531829/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com