float 和 double 常量比较

float and double constant comparing

来自http://www.cprogramming.com/tips/tip/difference-between-float-and-double

In c++ any value like 4.12 is treated as a double by default. Comparing floats and doubles can be a tricky business because of the difference in precision leading to minute errors. For example:

float a = 4.12;

if(a == 4.12)
{
    cout << "hello";
}
else
{
    cout << "bye";
}

This will show you the output as "bye 4.12"

Why?

Because by default 4.12 is a double (such as in the if statement or in the assignment to our variable), but storing it in a float it loses some precision, and so comparing then comparing a double with a float lead to microscopic changes in the precision of the number--remember that floats and doubles are not precise.

Two lessons here: one is that floating point numbers shouldn't be compared directly most of the time, and the other is that the default size and type of a hard-coded floating point number is double.

事情是'you should not do comparing float variable and double constant'。

所以我的问题是比较 float 变量和 float 常量后跟 'f' 可以吗?

像这样。

if(a == 4.12f)

comparing float variable and float constant followed by 'f' is ok?

还是很危险的。与您的 float/double 示例不同,a 的每个可能值都可能失败,实际上 a 的一个值 a == 4.12f 将是 true,但根据您设置 a 的方式,它可能不匹配 4.12f,即使您希望它匹配。例如:

#include <iostream>
#include <iomanip>

int main()
{
    float f = 4.14;
    f -= 0.01;
    f -= 0.01;
    std::cout << std::boolalpha << (f == 4.12f) << '\n';
}

ideone.com here 上输出:

false

标准确实保证在某些情况下会使用最接近的表示,因此如果您直接分配 float a = 4.12f;,那么之后的 a == 4.12f 必然是 true,并且第 26.5 节。 1.4 保证,如果您流出 a 并将文本流回另一个 float,它们将在之后进行比较。

无论如何,如果你觉得你必须依赖这样的东西,请检查 Standard/docs 以了解你正在考虑的具体用法。