gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:28:18 25 4
gpt4 key购买 nike

给定 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com