As mentioned earlier, C++ converts intβs to doubleβs automatically if necessary, because no information is lost in the translation. On the other hand, going from a double to an int requires truncating the value and produces a warning.
To remove this warning, you can do a typecast. Typecasting is so called because it allows you to take a value that belongs to one type and βcastβ it into another type (in the sense of molding or reforming, not throwing).
In C++, the way ask the compiler to do a typecast is to write static_cast<TYPE>(VALUE). When you write that, you are essentially saying βI know this looks potentially dangerous, but please go ahead and convert VALUE to type TYPE and do not warn me about it.β This is known as an explicit conversion because you are explicitly (visibly) doing the cast. Here is an example of an explicit conversion of a double value to the int type using static_cast<int>(VALUE):
Note that the static_cast does not change the value of the variable pi. it makes a copy of the value and converts it to the new type (int). The result is exactly the same as if we wrote int x = pi; on line 7 except there is no warning!
Using static_cast clearly communicates to both the compiler and other programmers that you are intentionally doing a potentially dangerous conversion (and thus hopefully are aware of the consequences!)
It is possible to type cast an integer value into a double using static_cast<double>(VALUE). Normally, it is not necessary to do so as the compiler will implicitly do the conversion without complaining. But sometimes it is useful to cast an integer to a double in order to force floating-point math. The following example does this to get a decimal answer for 1/3 in the second line of output:
As the line is evaluated, the static_cast happens first. It converts 1 to 1.0. Then the division takes place and it now says 1.0 / 3. Since there is at least one floating-point value involved, C++ does floating-point math.
#include <iostream>
using namespace std;
int main() {
int a = 1.5;
double b = a + 1.5;
double c = 2.4;
double d = 1/5;
int e = c * c;
double f = static_cast<int>(c);
}
Your final grade consists of your average performance on three exams. Your professor is using C++ to grade the exams and allows you to choose which method youβd like your exam to be graded.
Method 1 throws away the .8, .7, and .6 before averaging, while Method 2 averages first and then throws away the decimal part of the final result. The first method produces a grade of 82 while the second produces a grade of 83.
Method 2: the rounding happens at the very end, so my grade will be higher!