
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Assign Integer to Float and Comparison in C/C++
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
#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
#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
#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