hi plz i have a problem i have a h.w to be done & my code have something wrong so plz try to help me
the program wants the user to enter numbers until the user user enters a negative number then the program stops & output : max. no. ,min no. & avg .
& here is the code :
-
#include<iostream>
-
using namespace std;
-
void main()
-
-
{
-
float n=1;
-
float x;
-
float max;
-
float min;
-
-
-
cout<<"Enter the numbers separated by spaces: ";
-
cin>>x;
-
if(x>=0)
-
{max=x;
-
min=x;}
-
-
cin>>x;
-
while(x>=0)
-
{
-
if(x>max)
-
max=x;
-
-
if(x<min)
-
min=x;
-
-
cin>>x;
-
-
n++;
-
}
-
-
float avg=1;
-
float sum=0;
-
sum=sum+x;
-
avg=sum/n;
-
-
-
-
cout <<"Maximum:"<<max<<endl<<"Minimum:"<<min<<endl<<"Average:"<<avg<<endl;
-
-
-
}
so what's wrong with it plz answer me as soon as u can
Please add [code] tags around your code. Also read the following :
http://www.thescripts.com/forum/faq.php?faq=posting_guidelines#faq_how_to_ask_a_qu estion
Coming to errors in your code :
1. The value of variable 'n' is incorrect.
Lets see the flow of the code. By the time line 25 of your code gets executed you have read and analyzed two input values. As the value of n is 1 at this point of time, you should first increment the value of 'n' and then read the next input. So n++ should be before cin>>x(line 27)
2. Value of sum will be incorrect.
The variable 'sum' is being used to add up all the inputs except the last one. So the statement sum = sum + x should be executed whenever you have analyzed a valid value of 'x'. In you code the value of 'sum' will be the last value input for 'x' which will also be a negative value(resulting in a negative average)
I'll also tell you that you should declare and initialize 'sum' before reading the first input.
With this you should be able to figure out at what all places you should add the sum = sum + x statement.