[英]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 聲明為浮動,這還不夠嗎?
#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
。 這還不夠嗎?
抱歉不行。
ISO/IEC 9899:2017 §6.5.5 6 規定:
當整數被除時,
/
運算符的結果是代數商,其中任何小數部分都被丟棄。 105)如果商a/b
是可表示的,則表達式(a/b)*b + a%b
應等於a
[...]105)這通常被稱為“向零截斷”。
翻譯:兩個整數相除的結果是一個整數。
即使將它分配給float
或double
變量也不夠,它會在分配之前被截斷,解決方案是將小數表達式中的一個操作數轉換為 float 或 double,就像您所做的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.