This tutorial will teach you how to use integers in C++.
Integers
Integers are whole numbers such as -1, 0, 1, etc
Integers can't have decimal fractions :
Integer: 44
Float: 44.551
Round Down ( Truncation )
When a floating point number is assigned to an integer variable, the decimal fraction is removed.
This is called truncation :
#include <iostream> using namespace std; int main() { int int_var = 5.22; float flo_var = 5.22; cout << "int_var = " << int_var << endl; cout << "flo_var = " << flo_var << endl; return 0; }
If you need the decimal fraction included, use a float variable instead of an integer variable.
Integer Division
Whenever two integers are divided, the answer is always an integer, never a floating point number.
This is called integer division :
#include <iostream> using namespace std; int main() { cout << "5 / 2 = " << 5 / 2 << endl; return 0; }
Only if one or both of the numbers involved in the division is a floating point number will the decimal fraction be included :
#include <iostream> using namespace std; int main() { cout << "5 / 2 = " << 5 / 2.0 << endl; return 0; }
Note that 2.0 is a floating point number, even though it has the same value as 2.
#include <iostream> using namespace std; int main() { if ( 2 == 2.0 ) { cout << "2 equals 2.0" << endl; } else { cout << "2 does not equal 2.0" << endl; } }
Limits
There are three kinds of integer variables : short, int, and long.
Each can be signed or unsigned.
Each of these has a minimum and maximum value :
| Integer Type | Minimum Value | Maximum Value |
|---|---|---|
| short (signed) | -32767 | 32767 |
| short unsigned | 0 | 65535 |
| int (signed) | -32767 | 32767 |
| int unsigned | 0 | 65535 |
| long (signed) | -2147483647 | 2147483647 |
| long unsigned | 0 | 4294967295 |
#include <iostream> using namespace std; int main() { short sshrt_var = 32767; short unsigned ushrt_var = 65535; int sint_var = 32767; int unsigned uint_var = 65535; long slong_var = 2147483647; long unsigned ulong_var = 4294967295; cout << "short (signed) : " << sshrt_var << endl; cout << "short unsigned : " << ushrt_var << endl; cout << "int (signed) : " << sint_var << endl; cout << "int unsigned : " << uint_var << endl; cout << "long (signed) : " << slong_var << endl; cout << "long unsigned : " << ulong_var << endl; return 0; }
| Categories: Beginner Tutorials : Tutorials |