3.5和3.5f在C++中是否相同?

Abh*_*pta 5 c++ floating-point number-formatting

可能重复:
浮点数与浮点字面值的比较中的奇怪输出
为什么比较double和float导致意外结果?

在下面的代码中我希望答案是"不相等",因为默认情况下3.5 应该是doubleC++,但结果是"相等".

声明float a=3.5ffloat a=3.5?有什么区别?

#include<iostream>
using namespace std;

int main()
{
    float a=3.5;
    if(a==3.5)  
        cout<<"equal"<<endl;
    else
        cout<<"Not equal"<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 14

没有.

类型3.5是,double而类型3.5f是浮动.所以他们不能保证价值相等.

#include<iostream>

void f(double) { std::cout << "it is double" << std::endl; }
void f(float)  { std::cout << "it is float" << std::endl; }

int main()
{
   f(3.5);
   f(3.5f);
}
Run Code Online (Sandbox Code Playgroud)

输出:

it is double
it is float
Run Code Online (Sandbox Code Playgroud)

  • `3.5 == 3.5f`*由IEEE754保证,大多数"正常"系统使用这些天. (2认同)