The sum of n terms of fractional expression is an integer when it should be a float

╄→гoц情女王★ 提交于 2021-02-11 14:44:10

问题


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 when term = 1/n. I have declared term as float. 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 quotient a/b is representable, the expression (a/b)*b + a%b shall equal a [...]

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!