| C Tutorial | Int vs floating arithmatic | |||
|
Introduction to C language Integer types Char constants Int constants Type combination and promotion Int overflow Floating point types Comments Variables Assignment operator Truncation Int vs float arithmatic Mathematical operators Unary Increment Operators Pre and Post Variations C Programming Cleverness and Ego Issues Relational Operators Logical Operators Bitwise Operators Other Assignment Operators
|
Here's an example of the sort of code where int vs. float arithmetic can cause problems. Suppose the following code is supposed to scale a homework score in the range 0..20 to be in the range 0..100.
{ int score; ...// suppose score gets set in the range 0..20 somehow score = (score / 20) * 100; // NO -- score/20 truncates to 0 ...
Unfortunately, score will almost always be set to 0 for this code because the integer division in the expression (score/20) will be 0 for every value of score less than 20. The fix is to force the quotient to be computed as a floating point number... score = ((double)score / 20) * 100; // OK -- floating point division from cast score = (score / 20.0) * 100; // OK -- floating point division from 20.0 score = (int)(score / 20.0) * 100; // NO -- the (int) truncates the floating // quotient back to 0
|
|