You don't count the first thing you read, but you count the last thing twice. So you get the count right by accident, but of course get the sum wrong unless the first and last values happen to be the same.
You read something into num
and then enter the loop. The first thing your loop does is read into num
again, discarding the previous value. So the first value doesn't get counted. You then increment count
and add it to sum
whether or not the read succeeded, which counts the last value twice.
You want this:
myInput >> num;
while (myInput.good())
{
// First count the value that we just read
count++;
sum += num;
// Then read the next value
myInput >> num;
}
No comments:
Post a Comment