float和double的区别

Differentiate between float and double

//assume there is no Print(double dValue)
void Print(unsigned int nValue);
void Print(float fValue);
Print(3.14159);

Print(3.14159) 不应该与 Print(float) 匹配吗?

取而代之的是,这段代码导致了不明确的匹配

3.14159 数字文字是 double,而不是 float。 C++有两种选择:

  • double转换为unsigned int,并调用第一个重载
  • double转换为float,并调用第二个重载

两种选择都需要相同数量的转换,C++ 会报错。

您可以通过在文字末尾附加 F 来解决此问题:

Print(3.14159F);
//           ^

现在第一个选择仍然需要floatunsigned int的转换,而第二个选择可以不进行转换;因此,第二个重载 "wins".

Is 3.14159 a double ?

是的,是的。

How to differentiate between float and double ?

使用3.14159f使常量为float。使用3.14159使常量成为double.