Advantages and Disadvantages of Floating-Point Numbers

Floating-point numbers have two advantages over integers. First, they can represent values between integers. Second, because of the scaling factor, they can represent a much greater range of values. On the other hand, floating point operations usually are slightly slower than integer operations, and you can lose precision. Listing 3.9 illustrates the last point.

Listing 3.9. fltadd.cpp

// fltadd.cpp -- precision problems with float#include <iostream>int main(){    using namespace std;    float a = 2.34E+22f;    float b = a + 1.0f;    cout << "a = " << a << endl;    cout << "b - a = " << b - a << endl;    return 0;}

The program in Listing 3.9 takes a number, adds 1, and then subtracts the ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.