2

i have this problem from a beginning c sharp book this for conversion between Fahrenheit and Celsius.

    private void button1_Click(object sender, EventArgs e)
{
    float fahr, cel;
    if (Celsius.Checked == true)
    {
        fahr = float.Parse(textBox1.Text);
        cel = (5/9)*(fahr-32);
        richTextBox1.Text = "The Degree in Celsius is:" + cel.ToString() + Environment.NewLine + "cool isn't it!?";
    }
    else if (Fahrenheit.Checked == true )
    {
        cel = float.Parse(textBox1.Text);
        fahr = ((9 * cel)/5)+ 32;
        richTextBox1.Text = "The degree in Fahrenheit is:" + fahr.ToString() + Environment.NewLine + "cool is it!?";
    }

when i want to get Celsius from a Fahrenheit it keeps giving me 0 even though the formula appears to be true to me. what's wrong here?
because i think the problem lies here:

        if (Celsius.Checked == true)
    {
        fahr = float.Parse(textBox1.Text);
        cel = (5/9)*(fahr-32);
        richTextBox1.Text = "The Degree in Celsius is:" + cel.ToString() + Environment.NewLine + "cool isn't it!?";

maybe i have something wrong with Order of Ops but i think it's True? thanks for help.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user527825
  • 23
  • 1
  • 5

2 Answers2

7

Try

5.0F/9.0F

You are otherwise using integer arithmetic, where 5/9 is zero.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

Try putting another cast there just to be sure, like this:

cel = ((float)5/9)*(fahr-32);

Most probably 5/9 evaluate as ints and gives 0. Other option would be like this:

cel = (5f/9f)*(fahr-32);
Liviu Mandras
  • 6,540
  • 2
  • 41
  • 65
  • it worked , this cel = ((float)5/9)*(fahr-32); have worked ? is it treating 5/9 as a fraction (rational number) if the numerator less than the denominator and or if it's a fraction wiht integers only in both num and denom? – user527825 Dec 27 '10 at 10:38
  • In a division operation at least one operand has to be of type float in order for the entire result to be considered of type float. The size of the numbers does not matter. By using (float)5 i actually convert the integer 5 to a float value of 5.0, then divide it by integer 9. Since 5.0 is now obviously float the result will be a float number. – Liviu Mandras Dec 27 '10 at 10:44
  • A small note; this is all handled by the compiler, not the runtime - there is no runtime cast. (float)7 is identical to 7F – Marc Gravell Dec 27 '10 at 10:56