4

I just started learning C# , i am trying a program which takes temperature in fahrenheit and converts into celsius and in the the third step converts the celsius back into fahrenheit(to verify the math) I have used the following code in order to perform the above function

Console.Write("Enter Your Temperature in fahrenheit  : ");
float faren = float.Parse(Console.ReadLine());
float cel = (faren - 32)*(5/9);
float farenconv = 32 + (cel * 9 / 5);
Console.WriteLine("Orignal Temperature : " + faren);
Console.WriteLine("Converted in celsuis : " + cel);
Console.WriteLine("Converted Back in fahrenheit  : " + farenconv);

Now the problem is i am getting cel = 0 as an output no matter, what i enter as fahrenheit but when i remove the *(5/9) it works fine , does any one have any clue .

Christos
  • 53,228
  • 8
  • 76
  • 108
johnny
  • 171
  • 1
  • 12
  • 4
    5 and 9 are both integers. So 5/9 is performed in integer arithmetic... just change it to 5f/9f and you should get the right answer. – Jon Skeet Mar 31 '14 at 10:25
  • possible duplicate of [Conversion Between Fahrenheit and Celsius ISSUE](http://stackoverflow.com/questions/4538073/conversion-between-fahrenheit-and-celsius-issue) – Jon Skeet Mar 31 '14 at 10:26

2 Answers2

8

Use 5/9f that's a classic issue, when we do calculations with integer numbers.

Specifically, 5/9 equals to 0, since a/b, when a and b are integers and a<b is equal to 0.

Christos
  • 53,228
  • 8
  • 76
  • 108
2

To decide whether you're using integer or floating-point division, C# doesn't look at the type you're assigning to, it looks at the type of the divisor. Divide by an integer, it'll use integer division. Numeric literals are automatically integers if they don't contain a decimal point, so if you want float division you need to mark it as float. Adding f is shorthand for this, so 9f is a float. Similarly, 9d is a double, and 9m is a decimal.

So your code becomes

float cel = (faren - 32)*(5/9f);
float farenconv = 32 + (cel * 9 / 5f);
anaximander
  • 7,083
  • 3
  • 44
  • 62