Return to Topic Menu | Computer Science Main Page |  | Terms of Use

More Than You Wanted to Know
About Floating Point Variables

"Why do I tend to get warnings when I declare float variables?" 

     Visual C++ defaults all floating point numbers to doubles.  Since doubles are "larger" (or "smaller") than floats and require 8 bytes (floats require 4 bytes), the program is most likely thinking that you are casting - forcing a variable to take on the properties of another type.  It is trying to warn you that your "double" may lose some of its accuracy if changed to a smaller ranged type, such as a float

     Just remember:  To Visual C++, any number with a decimal point is a double.   Since the Advanced Placement Examination deals primarily with doubles, we also will concentrate on the use of doubles. 

Floating point variables involved with integer division are often confusing.

Consider the following situation:

int slices;        //representing slices of pizza at 375 calories per slice
float miles;    
//representing miles needed to jog off the pizza calories
miles = (375 * slices / 100):

1. If you declare slices as an int, and use
miles = (375 * slices / 100);

you have integer division taking place on the right hand side, since 375 and 100 are ints.  This integer calculation is completed and the result is placed into a float.  You get a warning of possible loss of data due to the integer division (in this case). You get the WRONG ANSWER displayed.

2. If you declare slices as an int, and cast the right hand side
miles = float(375*slices/100); 

you are forcing the machine to accept the value of the parenthesis as a float type.  But the parenthesis is computed first and the integer division occurs. Now, there is no warning, but the WRONG ANSWER is displayed.

3. If you declare slices as a float, you have prevented "integer division" from occurring and the CORRECT ANSWER is displayed.

In this case, declare
int slices, and double miles.  Make the computation line
miles = (375.0*slices/100);

The simple addition of the .0 makes 375.0 a double and solves all of the problems of integer division occurring.

Clear as muddy water, isn't it!!!   :- )