小数表达式的n个项的和应为浮点数时的整数 [英] The sum of n terms of fractional expression is an integer when it should be a float
问题描述
在下面的代码中,为什么我没有得到有效的结果,除非我输入 term = 1.0/n
,而不是输入 term = 1/n
.我已将term声明为float,这还不够吗?
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;
}
推荐答案
在下面的代码中,为什么我没有得到有效的结果,除非我输入
term = 1.0/n
,而不是输入term = 1/n
.我已经将term
声明为float
.那还不够吗?
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?
不幸的是.
ISO/IEC 9899:2017 §6.5.5 6 states:
除以整数时,
/
运算符的结果为代数商,其中舍弃了任何小数部分. 105)如果商a/b
是可表示的,表达式(a/b)* b + a%b
应该等于a
[...]
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)这通常被称为向零截断".
105) This is often called "truncation toward zero".
翻译:两个整数相除的结果是一个整数.
Translation: the result of this division of two integers is an integer.
即使将其分配给 float
或 double
变量也不够,它在分配之前将被截断,解决方案是将像您一样,在浮点数或双精度数中的分数表达式.
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.
这篇关于小数表达式的n个项的和应为浮点数时的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!