[RESOLVED] float valueA = 5/9; Always evaulates to 0
Hello,
I am writing a simple C program using Visual studio 2008.
And when I divide 5 / 9. I always get an zero. However, the correct value should be 0.5555.
Can anyone explain this?
Many thanks
Code:
//Calculate the temperature in celsius
int CalculateCelsius(int fahrenheit)
{
float valueA = 0;
int valueB = 0;
float celsius = 0;
valueA = 5 / 9; //Always displays zero
valueB = fahrenheit - 32;
celsius = valueA * valueB;
return (int) celsius;
}
Re: float valueA = 5/9; Always evaulates to 0
Since 5 and 9 are integers, the casting (or conversion) takes place after 5/9 is evaluated (which will be 0 in case of ints) and then converted to type float.
Try by converting either numerator or denominator to type float and that should work.
Code:
//one of them should work
valueA = 5f / 9; //or
valueA = 5 / 9f; //or
valueA = 5f / 9f;