【问题标题】:Conversion Between Fahrenheit and Celsius ISSUE华氏和摄氏之间的转换 ISSUE
【发布时间】:2010-12-27 10:29:51
【问题描述】:

我从一开始就有这个问题 这是华氏和摄氏之间的转换。

    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!?";
    }

当我想从华氏温度获取摄氏温度时,即使公式对我来说似乎是正确的,它也会一直给我 0。 这里有什么问题?
因为我认为问题出在此处:

        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!?";

也许我的行动秩序有问题,但我认为这是真的? 谢谢你的帮助。

【问题讨论】:

    标签: c# temperature unit-conversion


    【解决方案1】:

    试试

    5.0F/9.0F
    

    否则,您将使用整数算术,其中 5/9 零。

    【讨论】:

    • 哦,c^&b,我在这件事上对 c++ 没有问题 奇怪,我会尝试。但是等待它与这个 cel = (5/9)*(fahr- 32);
    • 呃,语言不一样!
    • aha 所以它只将任何真分数视为 0,就像舍入一样。
    • @user527825:实际上,我希望 C++ 的行为方式完全相同。
    【解决方案2】:

    尝试再放一个演员表来确定,像这样:

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

    很可能 5/9 评估为整数并给出 0。其他选项是这样的:

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

    【讨论】:

    • 成功了,这个 cel = ((float)5/9)*(fahr-32);有工作吗?如果分子小于分母,或者如果它是仅在 num 和 denom 中都包含整数的分数,是否将 5/9 视为分数(有理数)?
    • 在除法运算中,至少一个操作数必须是浮点类型,以便将整个结果视为浮点类型。数字的大小无关紧要。通过使用 (float)5 我实际上将整数 5 转换为浮点值 5.0,然后将其除以整数 9。由于 5.0 现在显然是浮点数,因此结果将是一个浮点数。
    • 一个小笔记;这一切都由编译器处理,而不是运行时 - 没有运行时强制转换。 (float)7 等同于 7F
    猜你喜欢
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    相关资源
    最近更新 更多