Arithmetic mean

why are the results at the end different when a is 0? when i type in a=1 and b=10 both results are 38.5 but when i type in a=0 and b=10 i get 32 and 39.5.

int a, b;
cin >> a >> b;
int sum1 = 0, sum2 = 0;

for (int i = a; i <= b; i++)
{

sum1 = sum1 + pow(i, 2);


}
int n = b - a + 1;
cout << float(sum1) / n << endl;

if (a == 0)cout << float(sum1) / b + 1 << endl;
else cout << float(sum1) / b << endl;
n becomes bigger when a is 0 instead of 1.
yes but i wrote when if a==0 than b+1, maybe i should try b=b+1
The expression float(sum1) / b + 1 is evaluated as (float(sum1) / b) + 1.

If you want to divide by b + 1 you need to surround it with parentheses: float(sum1) / (b + 1)
Yes i know i figured it out last night can't believe i missed that. Thx for the advise anyway.
because on the for loop, if a == 0, a the end sum1(a==0) = 1 + sum1(a==1);
Last edited on
Thx :D
Topic archived. No new replies allowed.