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

前端 未结 14 2033
名媛妹妹
名媛妹妹 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-21 23:47

    You cant avoid this as you're using floating point numbers with fixed quantity of bytes. There's simply no isomorphism possible between real numbers and its limited notation.

    But most of the time you can simply ignore it. 21.4==21.4 would still be true because it is still the same numbers with the same error. But 21.4f==21.4 may not be true because the error for float and double are different.

    If you need fixed precision, perhaps you should try fixed point numbers. Or even integers. I for example often use int(1000*x) for passing to debug pager.

提交回复
热议问题