本文介绍了除双打时精度C#损失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这已经再次讨论了一次,但我似乎无法得到,甚至双打的一步师的最简单的例子,导致在C#中预计,未四舍五入的结果 - 所以我想知道是否也许有一些如编译器标记或别的东西,怪我没有想到的。考虑这个例子:

 双V1 = 0.7; 
双V2 = 0.025;
双重结果= V1 / V2;

在我的最后一行后突破并检查它在VS调试器,结果的价值是27.999999999999996。我知道,我可以通过改变解决它十进制,但是那是不可能在周边项目的情况。这难道不奇怪,两个低精度双打这样不能分割到28正确的价值?是唯一的解决方案,真正Math.Round结果呢?


解决方案

No, not really. Neither 0.7 nor 0.025 can be exactly represented in the double type. The exact values involved are:

0.6999999999999999555910790149937383830547332763671875
0.025000000000000001387778780781445675529539585113525390625

Now are you surprised that the division doesn't give exactly 28? Garbage in, garbage out...

As you say, the right result to represent decimal numbers exactly is to use decimal. If the rest of your program is using the wrong type, that just means you need to work out which is higher: the cost of getting the wrong answer, or the cost of changing the whole program.

这篇关于除双打时精度C#损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:38