[Courses] [C] Beginner's Lesson Four: K's Answers to Exercises
Akkana
akkana at shallowsky.com
Sat Oct 12 14:42:28 EST 2002
KWMelvin writes:
> 1. /* ex4-1.c -- convert degress C to degrees F */
[ ... ]
> degF = (9 / 5) * degC + 32;
This caught my eye: if you're wondering why the program sometimes
gives the wrong answer, it lies here. Notice that 9 and 5 are both
integers: the compiler sees two integers, and assumes that it can
get away with doing only integer math. So this ends up being:
degF = 1 * degC + 32;
which of course isn't what you want.
If you change it to require floating point math:
degF = (9. / 5.) * degC + 32;
then presto, it gets the right answer! (Actually, adding the decimal
point to either the 9 or the 5 should do it; it shouldn't need both.)
This point applies to some of the other sample programs, too.
Minor point: you don't actually have to initialize degF to zero,
because you set it again before anyone ever checks it.
It doesn't hurt anything, though.
...Akkana
More information about the Courses
mailing list