C#浮点问题 [英] C# Floating point problem

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

问题描述

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Decimal d = 4.0m / 3.0m;            //same problem in Double
            Console.Write((4m / d) == (3m));    //same problem in this code Console.Write((4m / d).Equals(3m));
            Console.ReadLine();
            //expected output : True
            //actual output : False
        }
    }
}



我不知道如何解决这个问题.有人知道如何解决吗?



I don''t know how to solve this problem. Does anyone know how to solve it?

推荐答案

尝试将您的比较更改为Math.Round(4m/d, 27) == 3.
Try changing your comparison to Math.Round(4m/d, 27) == 3.


您必须使用舍入
you must use rounding
static void Main(string[] args)
        {
            Decimal d = 4.0m / 3.0m;
            Console.Write(System.Math.Round((4m / d),2) == (3m));
            Console.ReadLine();
        }


您正在此处处理小数位
在比较之前先四舍五入最终结果

Console.Write(Math.Round((4m/d),2,MidpointRounding.AwayFromZero)==(3m));

请记住,在计算的每个点(甚至就此而言存储它)都四舍五入不是一个好主意.考虑时四舍五入(用于显示或比较)

希望这就是您要寻找的东西
You''re dealing with decimals here
Just round off your final result before comparing

Console.Write(Math.Round((4m / d), 2, MidpointRounding.AwayFromZero) == (3m));

remember, its not a good idea to round off at every point of your calculation (or even when storing it for that matter). Round off when considering it (for display or comparison)

Hope this is what y''r looking for


这篇关于C#浮点问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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