繁体   English   中英

为什么我的代码在 c++ 中无限循环。 我的代码需要反复提示用户

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM