为什么在C中转换为int而不是所有双打

19 c floating-point

鉴于C代码:

#include <math.h>  
#include <stdio.h>  
int main(){  
 int i;  
 double f=log(2.0)/log(pow(2.0,1.0/2.0));  
 printf("double=%f\n",f);  
 printf("int=%d\n",(int) f);  
}
Run Code Online (Sandbox Code Playgroud)

我得到输出:

double=2.000000
int=1
Run Code Online (Sandbox Code Playgroud)

f显然至少是2.0.为什么施法值不是2?

Har*_*rry 33

因为double的值小于2

double=1.99999999999999978
int=1
Run Code Online (Sandbox Code Playgroud)

尝试一下,但这一次增加了一些精度

#include <math.h>  
#include <stdio.h>  
int main(){  
 int i;  
 double f=log(2.0)/log(pow(2.0,1.0/2.0));  
 printf("double=%0.17f\n",f);  
 printf("int=%d\n",(int) f);  
}
Run Code Online (Sandbox Code Playgroud)

第一次体验它时会感到困惑.现在,如果你试试这个

#include <math.h>  
#include <stdio.h>  
int main(){  
 int i;  
 double f=log(2.0)/log(pow(2.0,1.0/2.0));  
 printf("double=%0.17f\n",f);  
 printf("int=%d\n",(int) f);  
 printf("int=%d\n", (int)round(f));
}
Run Code Online (Sandbox Code Playgroud)

它将正确地舍入值.如果您查看手册页(至少在Mac上),您将看到以下注释...

round, lround, llround -- round to integral value, regardless of rounding direction
Run Code Online (Sandbox Code Playgroud)

他们的方向是什么意思,它在IEEE 754中都有规定.如果你检查不同的方法来舍入到整数...楼层被提到舍入朝向-ve infinity哪个是在这种情况下是1:)


Tho*_*mas 7

整数不会采用舍入值,但会截断.因此,如果f等于1.999999999999 [..] 9,则int值将为1.

此外,由于双重想要更准确,他将考虑到他可以显示的角色数量,即2.000000,将采用四舍五入的值.


dre*_*lax 7

浮点类型无法准确表示某些数字.即使在数学上,计算应该精确为2,对于IEEE754浮点,结果结果略小于2.有关更多信息,请参阅此问题.

如果通过指定%.20f而不是仅仅增加输出的精度%f,您将看到数字不完全是2,并且当打印精度较低时,结果只是四舍五入.

int但是,当转换为a 时,使用浮点类型的完全精度,并且由于它小于2,因此转换为整数时的结果为1.