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

标签 c

为什么这段代码的输出是“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/

相关文章:

c++ - 高斯消元的逻辑错误

c - 声明但未定义的函数的返回类型和参数中的不完整类型

c++ - 分配两个数组一次调用 cudaMalloc

c++ - POD 和模板

找不到-llibc

c - 将函数返回的数组分配给c中的变量

c++ - 初始化一个垃圾变量是真正的初始化还是只是一个赋值?

c - Frama-C 排序函数

c - while (getchar!= '\n');清除缓冲区的替代方法

c - 如何在 C 中将 unsigned int 值打印为时间字符串