Converting Between Fundamental Types Explicitly and Implicitly

The variable average is declared to be of type double (line 70 of Fig. 4.10) to capture the fractional result of our calculation. However, total and gradeCounter are both integer variables. Recall that dividing two integers results in integer division, in which any fractional part of the calculation is lost truncated). In the following statement:

double average = total / gradeCounter;

the division occurs first—the result’s fractional part is lost before it’s assigned to average. To perform a floating-point calculation with integers, we must create temporary floating-point values. C++ provides the static_cast operator to accomplish this task. Line 70 uses the cast operator static_cast<double>(total) ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.