给定 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);
}
我得到输出:
double=2.000000
int=1
f 显然至少为 2.0。为什么cast值不是2?
最佳答案
因为double的值小于2
double=1.99999999999999978
int=1
尝试一下,但这次要增加一些精度
#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);
}
第一次体验时会感到非常困惑。现在,如果你试试这个
#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));
}
它将正确地四舍五入该值。如果您查看手册页(至少在 Mac 上),您会看到以下评论...
round, lround, llround -- round to integral value, regardless of rounding direction
方向是什么意思,都在IEEE 754中说明了.如果您检查 different ways to round to an integer... floor 被提及为向 -ve infinity
舍入,在这种情况下是向 1
舍入 :)
关于c - 为什么在 C 中转换为 int 不是所有 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36879618/