[英]Why is my code infinitely looping in c++. My Code needs to repeatedly prompt the user
My Code 需要反复提示用户输入一个 integer 编号。 当用户不再想继续输入数字时,output 用户输入的所有正数的总和后跟用户输入的所有负数的总和。 这是我到目前为止所拥有的。
#include <iostream>
using namespace std;
int main() {
int a, sumPositive, sumNegative;
string promptContinue = "\nTo continue enter Y/y\n";
string promptNum = "\nEnter a numer: ";
char response;
while (response = 'y' || 'Y') {
cout << promptNum;
cin >> a;
if(a)
sumPositive += a;
else
sumNegative += a;
cout<< promptContinue;
}
cout<< "Sum of all the positive numbers is: "<< sumPositive<<endl;
cout<< "Sum of all the negative humbers is : "<< sumNegative<<endl;
return 0;
}
只是为了将其从未答复的列表中删除:
你的while
条件是错误的
while (response = 'y' || 'Y') {
将始终评估为true
。 这将导致无限循环。
它应该是
while (response == 'y' || response == 'Y') {
但是,这将始终评估为false
,因为未初始化response
。 通过将其从while...
更改为do...while
循环来解决此问题。 此外,您永远不会检索response
的值,因此我不确定您期望在那里发生什么。
#include <iostream>
using namespace std;
int main() {
int a, sumPositive, sumNegative;
string promptContinue = "\nTo continue enter Y/y\n";
string promptNum = "\nEnter a numer: ";
char response;
do {
cout << promptNum;
cin >> a;
if(a)
sumPositive += a;
else
sumNegative += a;
cout<< promptContinue;
cin >> response;
}
while (response == 'y' || response == 'Y');
cout<< "Sum of all the positive numbers is: "<< sumPositive<<endl;
cout<< "Sum of all the negative humbers is : "<< sumNegative<<endl;
return 0;
}
此示例中可能还有其他我尚未注意到的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.