MORE INFORMATION ON divide.c




The file divide.c is a a sample source file that contains an intent error in the function "divide()". The main function passes two integers to "divide()" to be divided by the function. The function does this properly. However, the division occurs according to the rules for integer division in the C family of programming languages. The problem with this is the accuracy of the division. As as a result of this integer division is always expressed as an integer itself. If a fractional part exists in the result, C truncates it without notifying the user.


EXAMPLE DATA
" a/b "

trial# "a=" "b=""a/b="reported results
12111
2120.50
31033.333~3


As one can see from trials "2" and "3" this characteristic of integer division leads to great inaccuracy.

To correct this error one could take a couple of different courses of action. Both courses require that the return type of "divide() " be changed from "int" to "float", "double", or some other type that can express numbers with fractional parts. One could then either change the type of one (preferably both to avoid the implicit recasting of the other) of the objects to a type that can express numbers with fractional parts (such as float, double, long double). However if it is necessary to use integers for the division, one must, recast one (preferably both, again to avoid the implicit recasting of the other) of the integers.

In this case, the return statement would read:
return ((float)x/(float)y);



Click here for the source code.