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 .
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With