Skip to main content

Section 4.1 Floating-Point Numbers

So what do you do if you want to divide 45 by 60 and get 0.75? Or if you want to store 3.14159? In C++, the answer is to use floating-point numbers, which represent values with decimal places. In C++, the default floating-point type is called double, which is short for “double-precision”. You can create double variables and assign values to them the same way we did for ints:
double pi = 3.14159;
double gpa = 3.86;
Once we have a double variable, we can do math with it. All of the operations work as you would expect:
Listing 4.1.1.
When printed, floating point values will be printed rounded to six significant digits. If the value is very large or small, it will be printed in scientific notation like 3.12345e+12 indicating \(3.12345 \times {10}^{12}\text{.}\) (We will learn how to change that formatting later.)

Note 4.1.1.

All the operations we have seen—addition, subtraction, multiplication, and division—work on floating-point values, although you might be interested to know that the underlying mechanism is completely different. In fact, most processors have special hardware just for performing floating-point operations. It generally takes longer to perform a given calculation using floating point hardware — 1/3 is quicker to compute than 1.0/3.0. That is one of the reasons why we have two different basic numeric types.

Checkpoint 4.1.1.

Checkpoint 4.1.2.

If you store the value 1,500,000 in a double, how will it be printed? (You can use Listing 4.1.1 to check by setting a variable to 1500000 and printing it.)
  • 15e+08
  • 1.5e+09
  • 15 x 10^8
  • 1.5 x 10^9
  • 1500000
You have attempted of activities on this page.