C#:奇怪的结果减去双打时 [英] C#: Weird outcome when subtracting doubles

查看:182
本文介绍了C#:奇怪的结果减去双打时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
在C#中不精确为什么浮点运算?

我一直在处理一些数字和C#和代码导致不同数量比人们所期望的以下行:

I have been dealing with some numbers and C#, and the following line of code results in a different number than one would expect:

double num = (3600.2 - 3600.0);



我预计NUM为0.2,然而,它竟然是0.1999999999998181。是否有任何理由为什么它是生产接近尾声,但仍然对十进制?

I expected num to be 0.2, however, it turned out to be 0.1999999999998181. Is there any reason why it is producing a close, but still different decimal?

推荐答案

这是因为是一个浮点数据类型。

This is because double is a floating point datatype.

如果你想更加准确,你可以切换到使用小数代替。

If you want greater accuracy you could switch to using decimal instead.

小数为m的字面后缀,所以使用十进制算术(并产生一个小数的结果),你可以写你的代码

The literal suffix for decimal is m, so to use decimal arithmetic (and produce a decimal result) you could write your code as

var num = (3600.2m - 3600.0m);

请注意,有缺点使用小数。这是一个128位的数据类型,而不是64位,它是一个尺寸双。这使得无论在存储器和处理方面更加昂贵。它也有一个更小的范围比双击

Note that there are disadvantages to using a decimal. It is a 128 bit datatype as opposed to 64 bit which is the size of a double. This makes it more expensive both in terms of memory and processing. It also has a much smaller range than double.

这篇关于C#:奇怪的结果减去双打时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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