为什么我的代码在c ++中无限循环.我的代码需要反复提示用户 [英] Why is my code infinitely looping in c++. My Code needs to repeatedly prompt the user
问题描述
我的代码需要反复提示用户输入一个整数.当用户不再希望继续输入数字时,输出用户输入的所有正数之和,然后输出用户输入的所有负数之和.这是我到目前为止所拥有的.
My Code needs to repeatedly prompt the user to input an integer number. When the user no longer wants to continue entering numbers, output the sum of all the positive numbers entered by the user followed by the sum of all the negative numbers entered by the user. Here is what I have so far.
#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;
}
推荐答案
只需将其从未答复的列表中删除即可:
Just to get this off the unanswered list:
您的 while
条件错误
while (response = 'y' || 'Y') {
将始终求值为 true
.这将导致无限循环.
Will always evaluate to true
. This will cause an infinite loop.
应该是
while (response == 'y' || response == 'Y') {
但是,由于未初始化 response
,因此这将始终为 false
.通过将其从 while ...
更改为 do ... while
循环来解决该问题.另外,您永远不会检索 response
的值,因此我不确定您期望在那里发生什么.
However, this will always evaluate to false
since response
is not initialized. Fix THAT by changing this from a while...
to a do...while
loop. Also, you never retrieve a value for response
, so I'm not sure what you're expecting to happen there.
#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;
}
此样本中可能还有其他我尚未注意到的错误.
There may be other bugs in this sample that I haven't yet noticed.
这篇关于为什么我的代码在c ++中无限循环.我的代码需要反复提示用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!