In my university's lecture today, we were given this:
input: 1, 2, 3, 0, 4
and two different codes
(1)
int x = 0;
int sum = 0;
int count = 0;
while (cin >> x && x != 0) {
sum += x;
count++;
}
cout << static_cast<double>(sum) / count;
(2)
int x = 1;
int sum = 0;
int count = 0;
while (x != 0 && cin >> x ) {
sum += x;
count++;
}
cout << static_cast<double>(sum) / count;
I understand the first code ends with an output of 2, but apparently the second output ends with an output of 1.5 (6/4). My confusion is over why the count is 4 if the loop becomes false after inputting zero - is it the location of the cin in the condition, the initialized x? I am confused. Thank you!