为什么 C# 中的浮点运算不精确? [英] Why is floating point arithmetic in C# imprecise?

查看:24
本文介绍了为什么 C# 中的浮点运算不精确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的程序打印它打印的东西?

Why does the following program print what it prints?

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

        Console.WriteLine(f1 > f2);
    }
}

输出是

false

推荐答案

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

Floating point only has so many digits of precision. If you're seeing f1 == f2, it is because any difference requires more precision than a 32-bit float can represent.

我建议阅读关于浮点,每个计算机科学家都应该阅读的内容

这篇关于为什么 C# 中的浮点运算不精确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆