gpt4 book ai didi

c - 为什么此代码的输出是 "BYE".. 而不是 "HI"

转载 作者:行者123 更新时间:2023-11-30 21:34:39 25 4
gpt4 key购买 nike

为什么这段代码的输出是“BYE”..而不是“HI”...

#include<stdio.h>
int main()
{
float i=1.1;
if(i==1.1)
printf("HI");
else
printf("BYE");
return 0;
}

由于 1.1 是浮点值,所以不应该是“HI”

最佳答案

float 无法精确表示。所以你不能直接将两个 float 等同起来。它通常与 epsilon 不同。

if(fabs(floatVarialbe-expectedValue) < **FLT_EPSILON**)
{
//statements to execute if they are equal
}

你应该使用 fabs 函数来获取绝对值[删除负号],它在 math.h 库中定义。FLT_EPSILON 是一个相对误差,它在 float.h 库中定义

Due to rounding errors, most floating-point numbers end up being slightly imprecise. As long as this imprecision stays small, it can usually be ignored. However, it also means that numbers expected to be equal (e.g. when calculating the same result through different correct methods) often differ slightly, and a simple equality test fails.

如果您想了解更多, What Every Computer Scientist Should Know About Floating-Point Arithmetic

关于c - 为什么此代码的输出是 "BYE".. 而不是 "HI",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20930728/

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