Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are 3.5 and 3.5f the same in C++? [duplicate]

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;
}
like image 762
Abhishek Gupta Avatar asked Apr 28 '12 07:04

Abhishek Gupta


2 Answers

Float are not an exact number. Comparing them with == is never an good idea. Here is why: What Every Computer Scientist Should Know About Floating-Point Arithmetic

like image 44
RvdK Avatar answered Sep 24 '22 02:09

RvdK


No.

The type of3.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
like image 119
Nawaz Avatar answered Sep 23 '22 02:09

Nawaz