Continue to Site

# [SOLVED]Why the answer for the sum and the average wrong??

Status
Not open for further replies.

#### Ashieboy

##### Member level 1
Code:
#include <iostream>
#include <fstream>
using namespace std;

int main(){
string line;
float x,sum=0,average,b;
int y=0,i,j,k=0;
float n1[1000];
float n2[1000];

ifstream myfile("sensor.txt");

if(myfile.is_open())
{
getline(myfile,line);
while(myfile.good())
{
myfile>>x;
n1[y]=x;
y=y+1;

}myfile.close();

for(i=0;i<y;i++)
{
sum=sum+n1[i];
}
average=sum/y;
cout<<"The sum of the number is "<<sum<<endl;
cout<<"The average is "<<average<<endl;
cout<<"\nThe number larger than average"<<endl;

for(i=0;i<y;i++)
{
b=n1[i];
if(b>average)
{
cout<<n1[i]<<endl;
}
else
{
continue;
}
}
}
else{cout<<"\nunable to open";}
}

#### Attachments

• 1.PNG
6.8 KB · Views: 83
• 2.PNG
9.8 KB · Views: 89

why do you have
Code:
    getline(myfile,line);
immediatly after opening the file? you are skipping the first line of the file

it is a good idea when reading data from a a file to print it out so you can check you are reading what is expected - you would probably have spotted the problem in this case

Ashieboy

V
Points: 2

### Ashieboy

Points: 2
you may also have another problem
Code:
    while(myfile.good())
{
myfile>>x;
n1[y]=x;
y=y+1;

}myfile.close();
although at the start of the loop the myfile.good() may return true the myfile>>x; statement can still fail, e.g. if the eof is reached

because the overloaded operator<<() function returns the ostream& as the function result you can test this to the if the << operation worked, e.g.
Code:
   while(myfile>>x)
{
n1[y]=x;
y=y+1;
cout << " y " << y << " data " << n1[y-1] << endl;
}
myfile.close();
if the myfile>>x fails it retuns a false and the while() exits

the above post #3 should have talked about the overloaded operator>>() (not operator<<() ) returning the istream& which is then tested to see if the input operation is sucessful
i.e. the function prototype looks like
Code:
std::istream& operator>>(std::istream& is, T& obj)

Status
Not open for further replies.