我只是遵循了一个关于do/while循环的简单c++教程,我似乎已经完全复制了教程中所写的内容,但我没有得到相同的结果。这是我的代码:
int main()
{
int c=0;
int i=0;
int str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15);
cout << "The sum of the numbers are: " << c << endl;
system("pause");
return (0);
}现在,在1次迭代之后,循环不再询问我的输入,只计算i的第一个初始输入的和。但是,如果我删除第二对cout/cin语句,程序就可以正常运行。
有人能指出我的错误吗?谢谢!
发布于 2012-05-29 23:41:24
如果你改变了
int str;至
char str;你的循环就像你想要的那样工作(在Visual Studio2010中测试过)。
不过,您可能还应该检查一下str == 'n',因为他们告诉您它们已经完成了。
发布于 2012-05-29 23:31:57
...and只计算我的第一个初始输入的总和。
这是意料之中的行为,因为您只是读取str而不是使用它。如果输入i >= 15,则循环必须中断,否则将继续。
发布于 2020-09-15 18:18:58
我觉得你想要这玩意
在这种情况下,总和c将小于15,并且如果用户输入y,则继续求和。
#include<iostream>
using namespace std;
int main()
{
int c=0;
int i=0;
char str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15 && str=='y');
cout << "The sum of the numbers are: " << c << endl;
return 0;
}https://stackoverflow.com/questions/10802157
复制相似问题