Are 3.5 and 3.5f the same in C++?

c++, floating-point, number-formatting

Solution

No.

The type of`3.5` is `double` whereas the type of `3.5f` is float. So they are not guaranteed to be equal in values.

#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);
}

Output:

it is double
it is float

Problem

Possible Duplicate: strange output in comparision of float with float literal Why comparing double and float leads to unexpected result? In following code I was expecting answer to be "Not equal", because by default the `3.5` should be `double` in C++, but the result was "equal". What is difference in declaring `float a=3.5f` and `float 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; } ```

Original source

Related problems