C#数学给出错误的结果! [英] C# Maths gives wrong results!

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

问题描述

我明白这个问题背后的原则,但它让我头疼认为这是在我的应用怎么回事,我需要找到解决方案,为

I understand the principle behind this problem but it's giving me a headache to think that this is going on throughout my application and I need to find as solution.

double Value = 141.1;
double Discount = 25.0;
double disc = Value * Discount / 100; // disc = 35.275
Value -= disc; // Value = 105.824999999999999

Value = Functions.Round(Value, 2); // Value = 105.82

我用双打来重新present相当小的数字。以某种方式在计算141.1 - 35.275结果的二进制重新presentation给出了许多这只是0.0000000000001出来。不幸的是,因为我再四舍五入这个数,这给了错误的答案。

I'm using doubles to represent quite small numbers. Somehow in the calculation 141.1 - 35.275 the binary representation of the result gives a number which is just 0.0000000000001 out. Unfortunately, since I am then rounding this number, this gives the wrong answer.

我读过有关使用小数代替双打,但我不能用十进制替换双的每个实例。有一些更简单的方法来解决这个问题?

I've read about using Decimals instead of Doubles but I can't replace every instance of a Double with a Decimal. Is there some easier way to get around this?

推荐答案

如果你正在寻找这自然是十进制数的确切重新presentations,你的将会的需要更换双击小数无处不在。你只是使用了错误的数据类型。如果你在使用处处为整数,然后发现你需要应付比支持更大的价值,你会做什么?这是相同的处理。

If you're looking for exact representations of values which are naturally decimal, you will need to replace double with decimal everywhere. You're simply using the wrong datatype. If you'd been using short everywhere for integers and then found out that you needed to cope with larger values than that supports, what would you do? It's the same deal.

不过,你真的应该尝试了解发生了什么事情下手......为什么值并不完全等于141.1,例如。

However, you should really try to understand what's going on to start with... why Value doesn't equal exactly 141.1, for example.

我对这个两篇文章:

  • Binary floating point in .NET
  • Decimal floating point in .NET

这篇关于C#数学给出错误的结果!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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