You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中double类型精度问题:如何避免输出超过1.0?

解决C#浮点数累加输出超过1.0的问题

这是因为double类型的二进制浮点精度限制——0.1无法被精确表示为二进制浮点数,多次累加后会出现精度误差,导致最后一次累加后count的值实际略大于1.0,从而输出了超过阈值的结果。

以下是几种可行的修改方案:

方案一:用整数计数避免浮点误差

通过整数计数再转换为目标浮点值,彻底规避累加带来的精度问题:

using System;

public class Program
{
    public static void Main()
    {
        int intCount = 0;
        // 0.1累加10次到1.0,对应整数从1到10
        while (intCount < 10)
        {
            intCount++;
            double count = intCount * 0.1;
            Console.WriteLine("{0:R}", count);
        }
    }
}

运行后会依次输出0.1到1.0,无精度误差和超阈值情况。

方案二:改用decimal类型精确计算

decimal是专门的十进制浮点类型,能精确表示0.1这类十进制小数,适合对精度要求高的场景:

using System;

public class Program
{
    public static void Main()
    {
        decimal count = 0.0m;
        while (count < 1.0m)
        {
            count += 0.1m;
            Console.WriteLine(count);
        }
    }
}

输出结果完全精确,最后一项为1.0,不会出现超阈值的情况。

方案三:调整循环逻辑适配浮点精度

如果必须使用double,可以通过以下方式适配浮点精度问题:

方式1:累加后判断再输出

using System;

public class Program
{
    public static void Main()
    {
        double count = 0.0;
        while (true)
        {
            count += 0.1;
            if (count > 1.0)
                break;
            Console.WriteLine("{0:R}", count);
        }
    }
}

方式2:用容差判断循环条件

设置一个极小的容差值,抵消浮点精度带来的误差:

using System;

public class Program
{
    public static void Main()
    {
        double count = 0.0;
        const double tolerance = 1e-10; // 极小的容差值
        // 判断累加后是否不超过1.0(带容差)
        while (count + 0.1 <= 1.0 + tolerance)
        {
            count += 0.1;
            Console.WriteLine("{0:R}", count);
        }
    }
}

内容的提问来源于stack exchange,提问作者Tamias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:50:29