Question
C++ Input a list of people's heights (in inches) from the user (terminated by a 0) and find the average height. The average should be
C++ Input a list of people's heights (in inches) from the user (terminated by a 0) and find the average height. The average should be displayed with a single value after the decimal, always showing. Do not allow the user to input a value less than 0 and use a while loop for input validation. What happens to your program if the first height input is 0? If this causes a problem, fix it!
Can someone help with the loops and input validation so it works correctly?
#include
#include
using namespace std;
int main()
{
//Set Decimal places to 1
cout << fixed << setprecision(1) << showpoint;
//Declare Variables
double heights; //The entered height
int total_heights = 1; //Number of heights entered
int total = 0; //Accumulator
double average; //Average of the entered heights
cout << "Enter the height of person 1 " << endl;
cout << "then enter 0 when finished " << endl;
cin >> heights;
if (heights <= -1)
cout << "Invalid entry!" << endl;
else
{
while (heights != 0)
{
total += heights;
total_heights++;
cout << "Enter the height of person " << total_heights << endl;
cin >> heights;
{
if (heights <= -1)
{
cout << "Invalid entry!" << endl;
break;
}
}
average = total / (total_heights-1);
cout << "The average of the entered heights is " << average << endl;
return 0;
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started