Type Conversion
In the last lesson, 7 / 2 gave 3, because both values were int. To get 3.5, one of the values must be a double. Changing a value from one type to another is called type conversion.
Convert on purpose with static_cast
static_cast<double>(x) gives you the value of x as a double. The variable x itself does not change.
#include <iostream>
using namespace std;
int main() {
int total = 7;
int people = 2;
cout << total / people << "\n";
cout << static_cast<double>(total) / people << "\n";
return 0;
}
Output:
3
3.5
In the second line, total became 7.0 before the division. When one side of / is a double, C++ converts the other side to double too, and the answer keeps its decimal part.
The conversion must happen before the division. Here it happens after:
int total = 7;
int people = 2;
cout << static_cast<double>(total / people) << "\n";
Output:
3
total / people was already 3, so converting 3 to a double does not bring the .5 back. Convert one of the values, not the result.
Conversions C++ does for you
C++ also converts some values without being asked. This is called an implicit conversion. Putting an int into a double is safe, because nothing is lost. The other way round is not safe:
double temperature = 36.6;
int degrees = temperature;
cout << degrees << "\n";
Output:
36
An int cannot hold the .6, so C++ dropped it. It did not round to 37. No error appeared, so this kind of mistake is easy to miss.
A char can also become an int. Inside the computer, every character is stored as a number, called its character code:
int code = 'A';
cout << code << "\n";
Output:
65
The code for 'A' is 65.
When you convert on purpose, write static_cast. It shows every reader that the conversion is not a mistake.
In the exercise, compute an exact average, with its decimal part.