本文介绍了为什么我看到一个双变量初始化为 21.4 之类的某个值作为 21.399999618530273?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
double r = 11.631;
double theta = 21.4;
在调试器中,这些显示为 11.631000000000000
和 21.399999618530273
.
In the debugger, these are shown as 11.631000000000000
and 21.399999618530273
.
我怎样才能避免这种情况?
How can I avoid this?
推荐答案
These accuracy problems are due to the internal representation of floating point numbers and there's not much you can do to avoid it.
顺便说一句,在运行时打印这些值通常仍然会产生正确的结果,至少使用现代 C++ 编译器是这样.对于大多数操作来说,这不是什么大问题.
By the way, printing these values at run-time often still leads to the correct results, at least using modern C++ compilers. For most operations, this isn't much of an issue.
这篇关于为什么我看到一个双变量初始化为 21.4 之类的某个值作为 21.399999618530273?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!