问题
The first part of the question is to write a program that:
prompts user to enter integer values and keep a running total.
#include<iostream>
using namespace std;
int main()
{
int n, sum = 0;
while(n != 0)
{
cout << "Enter number :";
cin >> n;
if(n <= 0)
break;
sum += n;
}
and the second part is:
Modify the previous program to print out the largest and smallest number read in as well as the average. Also change the prompt to show the number of numbers still to be entered.
#include<iostream>
using namespace std;
int main()
{
float n, sum=0.0, minimum=1.0, maximum=0.0, average;
int i = 0, x;
while(n != 0)
{
cout << "Enter number" << (i+1) << " :";
cin >> n;
if(n <= 0)
break;
sum += n;
i++;
if(n > maximum)
{
maximum = n;
}
if(n <= minimum)
{
minimum = n;
}
x = x + (i + 1);
}
cout << "Total=" << sum << endl;
average = sum / x;
cout << "Average=" << average << endl;
cout << "Maximum=" << maximum << endl;
cout << "Minimum=" << minimum << endl;
return 0;
}
My problem is that I'm not able to compute the average and show the number of numbers still to be entered. Can anyone help please?
回答1:
Problem is that you divide sum to x. Why you need this x? i is your count of inputed object, just divide sum to i;
One more bug, you define variable n and dont set value, and you want to compare it with 0. It can work incorrect.
#include<iostream>
using namespace std;
int main()
{
float n = 1,sum=0.0,minimum=1.0,maximum=0.0,average;
int i=0;
while(n!=0)
{
cout<<"Enter number"<<(i+1)<<" :";
cin>>n;
if(n<=0)
break;
sum+=n;
i++;
if(n>maximum)
{
maximum=n;
}
if(n<=minimum)
{
minimum=n;
}
}
cout<<"Total="<<sum<<endl;
average=sum/i;
cout<<"Average="<<average<<endl;
cout<<"Maximum="<<maximum<<endl;
cout<<"Minimum="<<minimum<<endl;
return 0;
}
来源:https://stackoverflow.com/questions/33187119/find-average-maximum-and-minimum-values-of-values-entered