English 中文(简体)
HCC C/C+++ 双重行为[重复]
原标题:GCC C/C++ double behavior [duplicate]
This question already has answers here:
Closed 12 years ago.

Possible Duplicate:
C++ double precision and rounding off

守则:

int main(void)
{
    double a = 12;
    double b = 0.5;
    double c = 0.1;

    std::cout.precision(25);
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
    std::cout << a + b << std::endl;
    std::cout << a + c << std::endl;

    return 0;
}

产出:

12
0.5
0.1000000000000000055511151
12.5
12.09999999999999964472863

Why does GCC represent 0.1 and 0.5 differently? When adding, they are represented differently. It seems 0.5 and whole numbers a represented differently that other floats. Or is this just something going on in the io library? What causes this behavior?

最佳回答

小数数数和数数有限的数字只能精确代表十倍功率之和的数字,二进制浮动点数只能精确代表二倍功率之和的数字。

在此情况下, 0.1 不能作为2的有限功率总和来代表, 而 > 0.5 12 可以( >0.5 等于2 -1 , >>12 等于2 3 3 +2 2

另一个例子是,0.75也可以在二进制浮动点中精确表示,因为它可以表示为2 -1 +2 -2

问题回答

0.1 无法在二进制中精确表示, 因为它不是2的功率, 而且必须用真正真正非常接近的数字来表示。 这就是为什么学生在比较浮动点数字和银行应用程序时, 几乎总是用两个整数、 美元数额和笔数存储钱。

这些问题的默认答案 :

< a href=>"http://perso.ens-lyon.fr/jean-michel.muller/goldberg.pdf" rel=“不跟随 nofollown noreferrer"> 每个计算机科学家应该了解的浮点算术

基本上,它就是浮动点编码的不准确性。您有大约17位重要数字,并且进行算术操作可以减少这些数字。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签