gpt4 book ai didi

c# - 为什么 C# 中的浮点运算不精确?

转载 作者:可可西里 更新时间:2023-11-01 08:14:20 25 4
gpt4 key购买 nike

为什么下面的程序会打印它打印的内容?

class Program
{
static void Main(string[] args)
{
float f1 = 0.09f*100f;
float f2 = 0.09f*99.999999f;

Console.WriteLine(f1 > f2);
}
}

输出是

false

最佳答案

float 只有那么多位数的精度。如果您看到 f1 == f2,那是因为任何差异都需要比 32 位 float 所能表示的更高的精度。

我推荐阅读 What Every Computer Scientist Should Read About Floating Point

关于c# - 为什么 C# 中的浮点运算不精确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/753948/

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