C++ 为什么我的代码在c++;。我的代码需要反复提示用户
我的代码需要反复提示用户输入一个整数。当用户不再想继续输入数字时,输出用户输入的所有正数之和,然后输出用户输入的所有负数之和。这是我到目前为止所拥有的C++ 为什么我的代码在c++;。我的代码需要反复提示用户,c++,C++,我的代码需要反复提示用户输入一个整数。当用户不再想继续输入数字时,输出用户输入的所有正数之和,然后输出用户输入的所有负数之和。这是我到目前为止所拥有的 #include <iostream> using namespace std; int main() { int a, sumPositive, sumNegative; string promptContinue = "\nTo continue enter Y/y\n"; string prompt
#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;
}
#包括
使用名称空间std;
int main(){
int a,SUM正,SUM负;
字符串promptContinue=“\n要继续,请输入Y/Y\n”;
字符串promptNum=“\n输入一个数字:”;
字符响应;
while(response='y'| |'y'){
cout>a;
如果(a)
SUM阳性+=a;
其他的
SUM负+=a;
不能只是为了从未回答的列表中删除此项:
您的while
状态错误
while (response = 'y' || 'Y') {
将始终计算为true
。这将导致无限循环
应该是
while (response == 'y' || response == 'Y') {
但是,由于响应
未初始化,因此该值将始终计算为false
。请通过将该值从while…
更改为do…while
循环来解决此问题。此外,您从未检索到响应
的值,因此我不确定您希望在那里发生什么
#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;
}
#包括
使用名称空间std;
int main(){
int a,SUM正,SUM负;
字符串promptContinue=“\n要继续,请输入Y/Y\n”;
字符串promptNum=“\n输入一个数字:”;
字符响应;
做{
cout>a;
如果(a)
SUM阳性+=a;
其他的
SUM负+=a;
cout>反应;
}
while(response='y'| | response='y');
coutresponse='y'| |'y'
应该是response='y'| | response='y'
另外,你在哪里请求response
的输入?顺便说一句,你应该初始化你的变量,特别是sumPositive'和sumPositive`只要在3Dave Yes重新阅读你的注释,当e程序启动时,当程序开始使用这些值时,这些值仍然为零的可能性很大,但是没有任何东西可以阻止优化编译器的混合操作对代码进行重新排序,从而使字符串
构造函数不能或调用>
和@Brannon