Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?

前端 未结 14 2034
名媛妹妹
名媛妹妹 2020-11-21 23:41
double r = 11.631;
double theta = 21.4;

In the debugger, these are shown as 11.631000000000000

14条回答
  •  伪装坚强ぢ
    2020-11-22 00:05

    This is partly platform-specific - and we don't know what platform you're using.

    It's also partly a case of knowing what you actually want to see. The debugger is showing you - to some extent, anyway - the precise value stored in your variable. In my article on binary floating point numbers in .NET, there's a C# class which lets you see the absolutely exact number stored in a double. The online version isn't working at the moment - I'll try to put one up on another site.

    Given that the debugger sees the "actual" value, it's got to make a judgement call about what to display - it could show you the value rounded to a few decimal places, or a more precise value. Some debuggers do a better job than others at reading developers' minds, but it's a fundamental problem with binary floating point numbers.

提交回复
热议问题