为什么我的代码不读取或遵循if
语句?
#include<iostream>
using namespace std;
int main (){
int sum = 0;
int integer;
while ((integer != -1) && (sum < 2000)){
int integer;
cout<<"Enter an integer: ";
cin>>integer;
if (integer == -1){
cout<<"Program was terminated.\n"<<"Your total sales are: "<<sum<<endl;
break;
}
else if (sum >= 2000) {
cout<<"Congratulations!"<<"Your total sales are: "<<sum<<endl;
break;
}
sum = sum + integer;
if (sum > 499){
cout<<"You're off to a good start!"<<endl;
}
if (sum > 999){
cout<<"You're halfway through!"<<endl;
}
else if (sum > 1499){
cout<<"You're almost there!"<<endl;
}
}
return 0;
}
应为:输入如下所示:输入整数:350、500、800、500美元
然后该出来的应该是这样的:
Enter an integer 350
" " 500
youre off to a good start
800
youre halfway through
500
Congratualations! Youre total sales are: 2150
现实:
Enter an integer: 350
Enter an integer: 500
You're off to a good start!
Enter an integer: 800
You're off to a good start!
You're halfway through!
Enter an integer: 500
You're off to a good start!
You're halfway through!
1条答案
按热度按时间34gzjxbg1#
您只想输入1个分支,因此需要一个
if
else if
链。你必须从最大的数字开始到最小的数字,因为如果你从小到大,如果进入一个分支,它将 * 总是 * 是第一个分支。
这是错误的,因为
integer
没有被初始化,因此这是未定义的行为。在某些情况下,它可能永远不会进入while循环,因为integer
保存了一些随机垃圾值,而这些值恰好是-1
。可以用一个简单的while true循环来替换它:
因为无论如何你都要在最后的分支中调用
break;
(这会跳出while
循环)。这也会修复一个bug,即循环会在最后的输出之前终止。您刚刚声明了两次
integer
,不需要第二次声明。完整代码:
读取Why is "using namespace std;" considered bad practice?