四舍五入的问题 [英] Rounding problem with double type

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

问题描述


可能重复:


我在C ++中遇到一个奇怪的问题。我创建了一个类型为Double的变量。然后,我做了一些计算,分配给其他变量的一些值,并将结果赋给我声明的双变量。它给了我一个很长的小数部分的结果。我希望它只有两位小数。并将其存储到变量中。但是,即使经过了几次尝试,我仍然无法将其舍入到小数点后两位。然后,我尝试了另一种方法来检查真正的问题是什么。我创建了一个Double变量并赋值为1.11。但是,当我通过放置一个断点来调试它,并为该变量添加一个监视时,我可以发现现在存储在变量中的值是1.109999999999。



我的问题是为什么这样表现?我们可以用什么方法将变量舍入到小数点后两位?为什么显示一个很长的小数部分,即使我们给一个只有两位小数的数字?

请建议一种存储数字的方法 - 无论是计算还是直接分配 - 这是一个双变量,而不是一个长整数的数字。

解决方案

,没有像1.11这样的东西,因为在内部,double使用二进制表示(与习惯于十进制表示的人类相反)。大多数有限的小数(例如1.11)在二进制中有无限的表示,但是由于内存是有限的,因为四舍五入而失去了一些精确性。



最接近你可以得到到1.11与双数据类型是1.1100000000000000976996261670137755572795867919921875,这是内部表示为0x3ff1c28f5c28f5c3。



您的小数点后两位的要求听起来像你用金钱工作。一个简单的解决方案是将美分存储在一个整数中(而不是美元的双倍):
$ b $ pre $ code int int = 111 ;

这样,您不会失去任何精度。另一个解决方案是使用一个专用的十进制数据类型。


Possible Duplicate:
Why don't operations on double-precision values give expected results?

I am experiencing a peculiar problem in C++. I created a variable of type Double. Then I did some calculations with some values assigned to other variables and assigned the result to the double variable I declared. It gave me a result with a long decimal part. I want it to round to only 2 decimal places. and store it into the variable. But even after several attempt rounding, I couldnt round it to 2 decimal places.

Then I tried another way to check what the real problem is. I created a Double variable and assigned it the value 1.11. But when I debugged it by putting a break point and added a watch for that variable, I could find that the value now stored in the variable is 1.109999999999.

My question is, why is it showing like that? Isnt there any way in which we can round the variable into two decimal places? Why is it showing a long decimal part even if we assign a number with just two decimal places?

Please suggest a way to store numbers - whether it is calculated or directly assigned - as it is, in a double variable rather than a number with a long decimal part.

解决方案

In the set of double values, there is no such thing as the number 1.11 because internally, double uses a binary representation (as opposed to humans who are used to a decimal representation). Most finite decimal numbers (such as 1.11) have an infinite representation in binary, but since memory is limited, you lose some precision because of rounding.

The closest you can get to 1.11 with the double data type is 1.1100000000000000976996261670137755572795867919921875, which is internally represented as 0x3ff1c28f5c28f5c3.

Your requirement of two decimal places sounds like you are working with money. A simple solution is to store the cents in an integer (as opposed to the dollars in a double):

int cents = 111;

This way, you don't lose any precision. Another solution is to use a dedicated decimal data type.

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

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