Assigning an integer to float and comparison in C/C++

CC++Server Side ProgrammingProgramming

The integer is a data type used to define a number that contains all positive, negative or zero non-fractional values. These cannot have decimals.

Float is a data type used to define a number that has a fractional value. These can have decimals also.

Now, we will check what will be the value of float and integer return by the compiler when we input the same value for both.

Example

 Live Demo

#include <iostream>
using namespace std;
int main(){
   float f = 23;
   unsigned int x = 23;
   cout<<"Float f = "<<f<<endl;
   cout<<"Integer x = "<<x<<endl;
   f = 0xffffffff;
   x = 0xffffffff;
   cout << "f = " << f << endl;
   cout << "x = " << x << endl;
   return 0;
}

Output

Float f = 23
Integer x = 23
f = 4.29497e+09
x = 4294967295

Here in this code, we can see that if we pass an integer value to a float then it will act as an integer and returns an integer value as output. But the max values for both of them come to be different.

Now, let’s see what if we initialize integer variable with float value.

Example

 Live Demo

#include <iostream>
using namespace std;
int main(){
   float f = 23.768;
   unsigned int x = 23.768;
   cout<<"Float f = "<<f<<endl;
   cout<<"Integer x = "<<x<<endl;
   return 0;
}

Output

Float f = 23.768
Integer x = 23

In this condition too the program compiled and run. The integer variable discarded the decimal point values of the initialize float value and gets initialized with the integer value of it.

Now, let's compare these values −

Example

 Live Demo

#include <iostream>
using namespace std;
int main(){
   float f = 0xffffffff;
   unsigned int x = 0xffffffff;
   if(f == x ){
      cout<<"TRUE";
   }
   else
      cout<<"FALSE";
   return 0;
}

Output

TRUE
raja
Published on 24-Oct-2019 10:41:40
Advertisements