c - 为什么在 C 中转换为 int 不是所有 double

标签 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);  
}

我得到输出:

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/

相关文章:

c++ - windows 和 unix/linux 下的 Socket 编程混淆

c - 使用 C 再现图像

xslt - XSLT 1.0 中的总和差异问题/错误

PHP - 将字符串转换为 float

c++ - 在 C(也许是 C++)中寻找数值/多媒体/信号处理基准

c - 是否有任何以类似于在 C 中使用 GTK 的小部件的方式打开/查看/与另一个程序交互?

c++ - 浮点运算,C 输出

linux - 是否有一个 header 提供类似于 uint64_t 的类型,用于 Linux 或 gcc 中的 float 和 double ?

c++ - 限制浮点精度?

c - Frama-C 代码切片器不加载任何 C 文件