Quote:
| Originally Posted by salem 3. Be mindful that 9/5 is done in integer arithmetic. |
Raja, that is a deceptively simple statement, but if you choose to ignore it then you will have to endure many hours of frustration.
You want 9/5 to give you a float value of 1.8, just as your electronic calculator would do. That's what's called
floating-point division (that "floating-point" is where the
float datatype got its name from).
But C also does
integer division, which is the kind that we were first taught in school, where you get an integer (AKA "whole number") quotient
and a remainder. So the integer division result of 9/5 would be
1 R 4. By the way and for your information, you use the
modulo operator, %, to get the remainder of an integer division.
Multiplying by the floating-point value 1.8, your result would be 1.8 times greater, a little less than twice the original, but multiplying by the integer division result of 1,
the result would be equal to the original value. Quite obviously, you want the floating-point division result and not the integer division one.
C uses the same symbol, / , for both integer and floating-point division, so then how does C know which kind of division you want it to use? Quite simply
through the datatypes of the operands you give it. If both operands (in this case, 9 and 5) are integer, then it's integer division, but if either if them are floating-point then it's floating-point division. At this point, you need to review the section of your textbook on
literals, specifically regarding the difference between int and float and double literals. For example, 42 would be int, whereas 42.0 would be double.
BTW, the same thing applies to multiplication ( * ), but in most situations it's difficult to detect the difference that it makes.