C#减不准确,即使小数点? [英] c# Subtract is not accurate even with decimals?

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

问题描述

我正在学习TDD,因此决定创建一个Calculator类开始. 我首先做了基本的操作,现在我正在使用平方根函数.

I'm learning TDD and, decided to create a Calculator class to start. i did the basic first, and now I'm on the Square Root function.

我正在使用此方法获取根 http://www. math.com/school/subject1/lessons/S1U1L9DP.html 我用很少的数字对其进行了测试,而且我始终能获得准确的答案............................................................................................ 很容易理解.

I'm using this method to get the root http://www.math.com/school/subject1/lessons/S1U1L9DP.html i tested it with few numbers, and I always get the accurate answers. is pretty easy to understand.

现在我遇到了一个奇怪的问题,因为有了一些数字,我就得到了正确的答案,而有了一些数字,我就没有了.

Now I'm having a weird problem, because with some numbers, im getting the right answer, and with some, I don't.

我调试了代码,发现使用减法时没有得到正确的答案.

I debugged the code, and found out that I'm not getting the right answer when I use subtract.

我使用小数来获得最准确的结果.

I'm using decimals to get the most accurate result.

当我这样做:

18 / 4.25

我目前正在:4.2352941176470588235294117647

应为:4.2352941176470588235294117647059(使用Windows计算器)

when it should be: 4.2352941176470588235294117647059 (using windows calculator)

在这条路的尽头,这是我最接近18根的地方:

in the end of the road, this is the closest i get to the root of 18:

4.2426406871192851464050688705 ^ 2 = 18.000000000000000000000022892

我的问题是:

我能得到比这更准确的信息吗?

Can i get more accurate then this?

推荐答案

4.2352941176470588235294117647包含29位数字.

decimal 被定义为具有28-29个有效数字.您不能在decimal中存储更准确的数字.

decimal is define to have 28-29 significant digits. You can't store a more accurate number in a decimal.

您从事的工程或科学领域是第30位或更多位数对总体计算的准确性具有重要意义?

What field of engineering or science are you working in where the 30th and more digits are significant to the accuracy of the overall calculation?

(如果您显示了更多实际的代码,这也可能会有所帮助.您显示的唯一代码是18 / 4.25,它不能在您的代码中作为实际表达式,因为第二个数字是double文字,并且在没有强制转换的情况下不能将表达式的结果分配给decimal.

(It would also, possibly, help if you'd shown some more actual code. The only code you've shown is 18 / 4.25, which can't be an actual expression in your code, since the second number is a double literal, and you can't assign the result of this expression to a decimal without a cast).

如果需要任意精度,则没有标准的"BigRational"类型,但是有一个 BigInteger .如果需要,可以使用它来构造BigRational类型(将分子和分母存储为两个单独的整数).一个关于为什么还没有标准类型的猜测是关于何时的决定,例如规范此类理性可能会影响绩效或平等比较.

If you need arbitrary precision, then there isn't a standard "BigRational" type, but there is a BigInteger. You could use that to construct a BigRational type if you need that (storing numerator and denominator as two separate integers). One guess of why there isn't a standard type yet is that decisions on when to e.g. normalize such rationals may affect performance or equality comparisons.

这篇关于C#减不准确,即使小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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