I’m trying to convert celsius to fahrenheit with C# ASP.net web forms in visual studio 2010.
I’m using a function to perform the conversion, including this code line:
return (celsius * (9 / 5)) + 32;
It doesn’t calculate right! If I put in celsius = 16, I’m getting 48.
I’ve tried doing the same in PHP, – I’m getting 60, which is what I’m suppose to get.
Any idea what could be wrong here?
You’re seeing
9 / 5being evaluated in integer arithmetic, giving the value of 1. So basically your expression is just adding 16.You want something like:
Or you could stay within integer arithmetic just by changing the evaluation grouping:
If your input and expected output are integers, I’d go with the latter. Obviously there’s now a greater risk of overflow… but only with very high temperatures 🙂
Note that this will always round down – if you want the mathemtically closest value, you’d probably want to still perform the arithmetic using floating point, then apply rounding, e.g.
Note that this will use banker’s rounding (round to even) for mid-points between two integers.