< Previous | Contents | Next >

Understanding Integer and Floating Point

Division

The symbol for division is the forward slash (/), so thats what I use in the next line of code. However, the output might surprise you. According to Cþþ (and that expensive gaming rig), 7 divided by 3 is 2. Whats going on? Well, the result of any arithmetic calculation involving only integers (numbers without fractional parts) is always another integer. And since 7 and 3 are both integers, the result must be an integer. The fractional part of the result is thrown away.

To get a result that includes a fractional part, at least one of the values needs to be a floating point (a number with a fractional part). I demonstrate this in the

Using Arithmetic Operators 15


next line with the expression 7.0 / 3.0. This time the result is a more accurate

2.33333.


Tra p

image

You might notice that while the result of 7.0 / 3.0 (2.33333) includes a fractional part, it is still truncated. (The true result would stretch out 3s after the decimal point forever.) It’s important to know that computers generally store only a limited number of significant digits for floating point numbers. However, Cþþ offers categories of floating point numbers to meet the most demanding needs—even those of computationally intensive 3D games.

image