问题
In the following code why don't I get a valid result unless I put term = 1.0/n
and not when term = 1/n
. I have declared term as float, Shouldn't that be enough?
#include <stdio.h>
int main()
{
float sum = 0, term;
int n, i;
printf("enter the value of n:\n");
scanf("%d", &n);
term = 1.0 / n;
for(i = 1; i <= n; i++)
{
sum = term + sum;
}
printf("Sum = %.3f\n", sum);
return 0;
}
回答1:
In the following code why don't I get a valid result unless I put
term = 1.0/n
and not whenterm = 1/n
. I have declaredterm
asfloat
. Shouldn't that be enough?
Unfortunately no.
ISO/IEC 9899:2017 §6.5.5 6 states:
When integers are divided, the result of the
/
operator is the algebraic quotient with any fractional part discarded.105) If the quotienta/b
is representable, the expression(a/b)*b + a%b
shall equala
[...]105) This is often called "truncation toward zero".
Translation: the result of this division of two integers is an integer.
Even if you assign it to a float
or double
variable it's not enough, it will be truncated before it's assigned, the solution is turn one of the operands in the fractional expression in a float or a double, like you did.
来源:https://stackoverflow.com/questions/60759755/the-sum-of-n-terms-of-fractional-expression-is-an-integer-when-it-should-be-a-fl