【发布时间】:2023-04-09 10:02:02
【问题描述】:
你能帮我解决这个问题吗
我正在运行一个简单的 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;
}
【问题讨论】:
-
第二个版本在这两种情况下都不能正确处理 -1。
-
这是因为您移动了年龄为阴性的测试。所以你最终会加上负年龄。准确地说是-1。
-
顺便说一句:这是在调试器下运行程序并查看每个步骤后包含哪些变量的完美示例。
标签: c++ loops increment decrement