为什么我不能乘以浮动? [英] Why can't I multiply a float?

查看:132
本文介绍了为什么我不能乘以浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/590822/dealing-with-accuracy-problems-in-floating-point-numbers\">Dealing在浮点数的精度问题

我很惊讶为什么我试着乘在C浮动(与GCC 3.2),它并没有这样做,因为我预料。作为一个例子:

I was quite surprised why I tried to multiply a float in C (with GCC 3.2) and that it did not do as I expected.. As a sample:

int main() {
  float nb = 3.11f;
  nb *= 10;
  printf("%f\n", nb);
}

显示:31.099998

Displays: 31.099998

我很好奇关于彩车的实现方式以及为什么会产生这种意外的行为?

I am curious regarding the way floats are implemented and why it produces this unexpected behavior?

推荐答案

首先,您可以乘花车。你的问题是不是乘法本身,而是你使用原来的号码。乘法可能会失去一些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.

这篇关于为什么我不能乘以浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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