-
logic question
Suppose a file has a sequence of integers:1 2 3 4 5 6
The following is the code. It should read all the integers and output averages of 4 integers until the file ends.
The output should be
2.5 ((1+2+3+4)/4)
3.5 ((2+3+4+5)/4)
4.5 ((3+4+5+6)/4)
Code:
string filename;
ifstream fin;
cin>>filename;
fin.open(filename.data());
int w,x,y,z,temp;
fin>>w>>x>>y>>z;
fin>>temp;
while (!fin.eof())
{
w=x; x=y; y=z; z=temp;
cout<<(w+x+y+z)/4;
fin>>temp;
}
fin.close();
}
I just can't get the logic in the while loop.
If w=x, why is the first integer not skipped?
-
> If w=x, why is the first integer not skipped?
I suppose your question is why it is being skipped.
The only explanation I find is that the first character in the file is 0, not a 1.
If the first character is anything but 0, then that code will be wrong and the solution would be to move w=x; x=y; y=z; z=temp; after the cout statement.
-
BTW (w+x+y+z)/4 is int
It cannot be 2.5
-
Thanks! Actually the code is the suggested solution of the task. Maybe there is a mistake.I wonder if w=x; x=y; y=z; z=temp; should be moved after the cout statement.
-
also the first fin>>temp;
can make a problem if the file contains only 4 values...
-
> Thanks! Actually the code is the suggested solution of the task. Maybe there is a mistake.I wonder if w=x; x=y; y=z; z=temp; should be moved after the cout statement.
If the first number in the file is not a zero, then it must.