Conversion Between Fahrenheit and Celsius ISSUE

心已入冬 提交于 2019-12-18 09:14:49

问题


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.


回答1:


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);



回答2:


Try

5.0F/9.0F

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



来源:https://stackoverflow.com/questions/4538073/conversion-between-fahrenheit-and-celsius-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!