1.2.3 Numbers

Like other languages, C++ has several different variable types for numbers. In this course, you will use two basic types, integer (int) to represent whole numbers and doubles (double) to represent decimal numbers.

Declaring and Initializing Numbers

Like Java, you can declare and initialize in one step, or declare and initialize later.

int num1 = 10;

double num2;
num2 = 11.5;

C++ allows you to declare and assign multiple values at once.

int num3, num4;
num3 = num4 = 15;

A Word of Caution

C++ as a language has fewer checks compared to Java or other languages. As you saw with accessing a string index that did not exist, C++ will also allow you to access a variable that has not been initialized. Other languages such as Java will throw an error if you try to access a variable before it has been initialized, but this is not the case in C++. When a variable is declared, a memory location is associated with that variable. If you access that variable before initializing it, you will get the last value stored in that memory location, which will not have any meaning to you.

Math with Integers and Doubles

Math operations work exactly the same as Java. A calculation with two integers results in a truncated integer:

  • Example: 15 / 10 โ†’ 1

A calculation with at least 1 double results in a double

  • Example: 15.0 / 10 โ†’ 1.5

Casting Numbers in C++

Casting numbers work exactly the same as Java. To cast a value, you include the type that you want to cast to inside of parentheses. When a value is cast, it creates a temporary version of the value in the new format, but does not change the original value.

int i = 5;
double d = (double) i;
int i2 = (int) d;

Casting To and From String

Casting strings to numbers uses a series of sto commands. The two most common that you will use are listed here:

  • stoi(num) - converts string to int

  • stod(num) - converts string to double

C++ doesnโ€™t allow implicit conversion from a number to a string. In order to use a number as a string, the to_string function needs to be explicitly called.

For example, if you want to concatenate a string and a number, you would do it like this:

int limit = 65;
string sign = "Speed Limit: " + to_string(limit);

Try This Example

Last updated