Thread: Farenheight to Celcius ch 3 View Single Post
January 2nd, 2011, 10:11 AM
DrPurdum
Friend of Wrox
 Points: 1,166, Level: 13
 Activity: 0%

Join Date: Sep 2008
Location: Indianapolis, IN, USA.
Posts: 234
Thanks: 0
Thanked 32 Times in 30 Posts
Temperature conversion problem

The problem is with the line:

Celcius = 5 / 9 * (Farenheit - 32);

When the compiler sees this line, it thinks: "Ok, I have integer constants 5, 9, and 32. It will perform the parenthesized calculation (Farenheit - 32) first. Because an integer constant is used, the expression is evaluated as an integer. Since the 5 and 9 are also viewed as integer constants, even thought the calculation evaluates to 5/9 = .5555555559, because the compiler thinks it's an integer expression which can't support decimal values, it sees the calculation as zero. It then multiplies the parenthesized expression (i.e., Farenheit - 32) as an integer result and then multiplies that by zero. The result will always be zero.

The correction is easy:

Celcius = 5.0 / 9.0 * (Farenheit - 32.0);

by adding the ".0" to each constant, the compiler now knows you want to perform floating point, not integer, operations. The result is that the double-precision operation on the right side of the assignment is now done as a floating point operation.

BTW, while it would not make much difference in this case, division is the slowest of the basic math operations. If this were in a lengthy loop, you could make it execute faster using:

Celcius = .5555555559 * (Farenheit - 32); // .5555555559 is 5/9

Note: The comment should be added, as it documents the "magic number". You could also use a numeric constant instead of the magic number:

const double FIVENINTHS = .555555555559;

and change the code to:

Celcius = FIVENINTHS * (Farenheit - 32); // .5555555559 is 5/9

I would still leave the comment in the code. I hope this helps.
__________________
Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)
 The Following 2 Users Say Thank You to DrPurdum For This Useful Post: igor01 (January 30th, 2011), RyanL (January 2nd, 2011)