math quirk

Hi, I ran into a quirk today. The global variable "temperature" has an initial value of 74 deg F. float t ; t = temperature ; t = (t - 32) * (5/9) ; // returns zero t = (t - 32) * .555555 ; // returns the correct value

Why would (t - 32) * (5/9) return zero?

Thank you, Steve

(5/9) is an integer expression that evaluates to 0. If you make it a float expression

t  =    (t - 32.0) * (5.0/9.0) ;

You will get what you are looking for.

Also, division is one of the slowest math operations, so if you have two constants like you do here, it's best to resolve the expression yourself with a constant (e.g., your .55555). While it won't make much difference here, it could if it's in a tight loop.

econjack: ... While it won't make much difference here, it could if it's in a tight loop.

it always better to have as much spare cycles as possible :)

Thank you, Steve

econjack: it's best to resolve the expression yourself with a constant (e.g., your .55555).

The compiler does a perfectly good job of this. It definitely evaluates 5.0/9.0 at compile time. There is no performance benefit to substituting 0.55555... for this division. There may even be a loss of precision when you do this.