Reputation: 11
When I give my n a value of 1 why does the result equal to 2 and not 3. Here is my code
#include <stdio.h>
int main()
{
int n;
float result;
scanf("%d", &n);
result = 1 + n/(2*n+1)*3/2;
while (n != 1)
{
result = result*(n-1)/(2*(n-1)+1);
n = n-1;
}
result = result * 2;
printf("%f", result);
return 0;
}
Upvotes: 0
Views: 200
Reputation: 993
Since n
is an int
, the math on the right side is done as integer math, not float. Then the results is promoted to float to store into result
.
result = 1 + n/(2*n+1)*3/2;
result = 1 + 1/3*3/2;
result = 1 + 1;
result = float(2);
Use float
constants to get it to actually calculate as a float.
result =1.0f + n/(2.0f*n+1.0f)*3.0f/2.0f;
Upvotes: 7