Не могли бы вы помочь мне в этом
Я использую простую программу на 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 будет добавлено к общему количеству, и пока цикл будет пропущен.
while(age != -1)
{
cout << "What is the age of the next person?" << endl ;
cin >> age;
total = total + age ;
}
То же самое относится и к остальной части кода. Если вы введете -1 в цикле, то он будет сначала добавлен к итоговому значению, а затем проверен и цикл завершится.
Таким образом, вы должны придерживаться своей первой версии.
В качестве упражнения вы можете поставить total = total + 1 после цикла. Который будет компенсировать -1. Но только как упражнение.
Других решений пока нет …