且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能乘以浮动?

更新时间:2023-11-06 10:56:46

首先,您可以乘花车。你的问题是不是乘法本身,而是你使用原来的号码。乘法可能会失去一些precision,但在这里,你乘以原来的号码开始失去了precision。

First off, you can multiply floats. The problem you have is not the multiplication itself, but the original number you've used. Multiplication can lose some precision, but here the original number you've multiplied started with lost precision.

这实际上是一个预期的行为。 浮动,则使用二进制重新presentation这意味着他们不能准确地重新present十进制值执行。

This is actually an expected behavior. floats are implemented using binary representation which means they can't accurately represent decimal values.

请参阅 MSDN 了解详情。

您还可以看到在浮动的描述,它有6-7显著位数字的准确性。在您的例子,如果你圆 31.099998 7显著的数字,你会得到 31.1 所以它仍然可以作为这里的预期。

You can also see in the description of float that it has 6-7 significant digits accuracy. In your example if you round 31.099998 to 7 significant digits you will get 31.1 so it still works as expected here.

双击课程类型会更准确,但还是舍入误差,由于它的二进制重新presentation,而你写的数字是小数。

double type would of course be more accurate, but still has rounding error due to it's binary representation while the number you wrote is decimal.

如果你想为十进制数字完全准确,你应该使用十进制类型。这种类型的如C#语言的存在。 http://msdn.microsoft.com/en-us/library/system .decimal.aspx

If you want complete accuracy for decimal numbers, you should use a decimal type. This type exists in languages like C#. http://msdn.microsoft.com/en-us/library/system.decimal.aspx

您也可以使用有理数重新presentation。使用两个整数,这将只要你可以重新present数量为两个整数的除法给你完全准确。

You can also use rational numbers representation. Using two integers which will give you complete accuracy as long as you can represent the number as a division of two integers.