#include <iostream>
using namespace std;
int main(){
int num=0;
int total=0;
cout<<"Enter many numbers as you like : "<<endl;
while (cin>>num){
if (num==0){
break;
cout<<"The sum is : " ;
total = total + num;
}
}
system("PAUSE");
return 0;
}
当我运行它时它会运行,当我输入零时,程序停止但它没有得到用户输入的数字的总和。请帮我解决这个问题。谢谢。 :)
答案 0 :(得分:0)
要打印数字,请执行以下操作:
cout<<"The sum is : " << total << endl;
答案 1 :(得分:0)
您需要将break;
语句作为条件if(...){...}
语句的最后一行。当程序到达break
语句时,它将退出while循环并继续执行程序结束。现在,在cout
写入新流之前退出循环并更新总数。
其次,您希望将total的值放在输出流上:
cout << "The sum is : " << total << endl;
目前,您只是打印出字符串"The sum is :"
此外,system("PAUSE");
是一个依赖于shell和OS的语句,通常不被视为良好的编码实践。您可能希望研究另一种方法来完成此任务:http://www.dreamincode.net/forums/topic/30581-holding-the-execution-window-open/
答案 2 :(得分:0)
#include <iostream>
#include <unistd.h>
int main() {
int num = 0,
total = 0;
std::cout << "Enter as many numbers as you like : " << std::endl;
while (std::cin >> num) {
if (num == 0) {
std::cout << "The sum is : " << total << std::endl;
break;
}
total += num;
}
return sleep(5);
}