问题描述
我比较了C中的简单浮点数和双精度值,特别是两者的值为8.7。现在我将8.7分配给每个变量,当我打印时,我得到这两个值的8.7000的结果。为什么编译器添加了这些零。而我想问的主要问题是有没有我看到的更多的数字,就像隐藏在尾随零之后一样。我读到,由于缺乏精度,我不应该像float这样进行比较,但是我觉得用这么小的数值肯定可以存储8.7,需要一定的准确度才能与另一个8.7值进行比较?我唯一担心的是,它实际上被表示在内存中的某个地方,例如8.70000003758或者某些东西,这是我的比较?我试图用%.20f打印,看看可能隐藏的任何进一步的数字,但我认为只是创建的数字,否则不是,因为数字的整体准确性变成8.6918734634834929或类似的东西。
不好的选择,因为8.7没有确切的二进制表示。
您的打印例程没有。
由于8.7没有精确的二进制表示。 (尝试写出2的整数幂的总和,你不能这样做。)
你以为错了。 1/3是小的,但没有精确的十进制表示,有限数字。无论一个值是大还是小都与一个特定基数中的数字位数是否完全一致。
,就像$ code> 0.333333333 一样代表1/3。
这可能只是一个错误。向我们显示代码。也许你试图输出一个双数,并将其留下 l
。
I'm comparing simple floats and doubles in C, specifically the value 8.7 for both of them. Now I assign 8.7 to each variable, when I print I get a result of 8.7000 for both values. Why has the compiler added these zeros. And the main question I wanted to ask was is there any further numbers that I'm not seeing, as in hidden after the trailing zeros. I read that I shouldn't do comparisons like this with float because of a lack of precision, but I thought with such a small value surely it can store 8.7 with a degree of accuracy needed to compare itself with another 8.7 value?
My only worry is that its actually being represented somewhere in memory as eg 8.70000003758 or something, which is throwing my comparisons off? I tried to printf with %.20f to see any further numbers that might be hiding but I think that just created numbers that were otherwise not there as the whole accuracy of the number changed to 8.6918734634834929 or something similar.
Bad choice, since 8.7 has no exact binary representation.
It hasn't, your print routine has.
Definitely, since 8.7 has no exact binary representation. (Try to write it out as the sum of integer powers of 2, you can't do it.)
You thought wrong. 1/3 is small but has no exact decimal representation with a finite number of digits. Whether a value is big or small has nothing to do with whether it can be represented exactly with a finite number of digits in a particular base.
Exactly, just as representing 1/3 as 0.333333333
would do.
That's probably just a bug. Show us that code. Perhaps you tried to output a double and left out the l
.
这篇关于C浮动和双重比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!