C++ 程序没有得到想要的输出

C++ program not getting desired output

你能帮我解决这个问题吗

我是 运行 一个简单的 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。

  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。但仅作为锻炼。