< previous page page_533 next page >

Page 533
Sometimes you can avoid adding two floating point numbers that are drastically different in size by carefully arranging the calculations in a program. Suppose a problem requires many small floating point numbers to be added to a large floating point number. The result is more accurate if the program first sums the smaller numbers to obtain a larger number and then adds the sum to the large number.
At this point, you may want to turn to the first Problem-Solving Case Study at the end of the chapter. This case study involves floating point computations, and it addresses some of the issues you have learned about in this section.
SOFTWARE ENGINEERING TIP
Choosing a Numeric Data Type
A first encounter with all the numeric data types of C++ may leave you feeling overwhelmed. To help in choosing an alternative, you may even feel tempted to toss a coin. You should resist this temptation, because each data type exists for a reason. Here are some guidelines:
1. In general, int is preferable.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
As a rule, you should use floating point types only when absolutely necessarythat is, when you definitely need fractional values. Not only is floating point arithmetic subject to representational errors, it also is significantly slower than integer arithmetic on most computers.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
For ordinary integer data, use int instead of char or short. It's easy to make overflow errors with these smaller data types. (For character data, though, the char type is appropriate.)
2. Use long only if the range of int values on your machine is too restrictive.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Compared to int, the long type requires more memory space and execution time.
3. Use double and long double only if you need enormously large or small numbers, or if your machine's float values do not carry enough digits of precision.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The cost of using double and long double is increased memory space and execution time.
4. Avoid the unsigned forms of integral types.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
These types are primarily for manipulating bits within a memory cell, a topic this book does not cover. You might think that declaring a variable as unsigned prevents you from accidentally storing a negative number into the variable. However, the C++ compiler does not prevent you from doing so. Later in this chapter, we explain why.
By following these guidelines, you'll find that the simple types you use most often are int and float, along with char for character data. Only rarely do you need the longer and shorter variations of these fundamental types.

 
< previous page page_533 next page >