请你帮我解决这个问题
我正在运行一个简单的c ++程序,虽然我可以按照书中的方式获得输出,但是当我以一种我认为在逻辑上正确的方式修改它时,我得不到正确的答案。初学者。
原创计划(工作):
#include <iostream>
using namespace std;
int main()
{
// make a program that finds the total of ages in a random family whose size we dont know
// we will ask for input from the user multiple times using a loop
// if user enters -1 program termintaes
int age;
int total = 0 ;
cout << "What is the age of the first person?" << endl ;
cin >> age;
while(age != -1)
{
total = total + age ;
cout << "What is the age of the next person?" << endl ;
cin >> age;
}
cout << "The total age is " << total << endl ;
return 0;
}
修改过的(不工作不知道为什么)
#include <iostream>
using namespace std;
int main()
{
// make a program that finds the total of ages in a random family whose size we dont know
// we will ask for input from the user multiple times using a loop
// if user enters -1 program termintaes
int age;
int total = 0 ;
cout << "What is the age of the first person?" << endl ;
cin >> age;
total = total + age ;
while(age != -1)
{
cout << "What is the age of the next person?" << endl ;
cin >> age;
total = total + age ;
}
cout << "The total age is " << total << endl ;
return 0;
}
答案 0 :(得分:0)
如果您为第一个条目输入-1,则在您的代码中。
cin >> age;
total = total + age ;
然后-1将被添加到total,而while循环将被跳过。
while(age != -1)
{
cout << "What is the age of the next person?" << endl ;
cin >> age;
total = total + age ;
}
其余代码也是如此。如果在循环内输入-1,那么它将首先添加到total,然后进行测试并循环退出。
所以你应该坚持使用你的第一个版本。 作为练习,你可以在循环后输入total = total + 1。这将补偿-1。但只是作为锻炼。