C++ Numbers
June 09, 2020 by Jane

Type Range Size Format Specifier
char Not usually used to represent numbers but can store -128 to 127 1 byte %c
int -2,147,483,648 to 2,147,483,648 4 bytes %d
unsigned int 0 to 4,294,967,295 4 bytes %u
short -32,768 to 32,767 2 bytes %d
unsigned short 0 to 65,535 2 bytes %u
long long -9,223,372,036,854, 775,808 to 9,223,372,036,854,775,807 8 bytes %ld
double

double-precision floating  point, range: +/- 10^308 with 15 sig figs

  • 1 bit for the sign
  • 11 bits for the exponent
  • 52 bits for the value
8 bytes %lf
float

single-precision floating point, range: +/- 10^38 with 7 sig figs

  • 1 bit for the sign
  • 8 bits for the exponent
  • 23 bits for the value
4 bytes %f

 

Beware of modulus of negative numbers:

E.g. a% n where a is negative will return a negative number. To get a number that is positive use n-1-(-a-1)%n where a is the number, n is divisor

 

Popular Math Functions:

 #include<algorithm>

  • max / min
  • abs
  • floor / ceil
  • sqrt / pow

 

Casting:

If we assign on variable of type double to another variable of type int we will probably get a warning about the implicit conversion. To write better and safer programs we should explictly cast the number if that is the intention.

E.g.

double my_double = 3.5

int my_integer = static_cast<int>(my_double)

 

Random Number Generation:

#include <ctime>

#include <cstdlib>
int main() {

    srand(time(0));

    int randInt = rand();

}