不能将类型“双精度”隐式转换为“浮点数”

本文关键字:双精度 浮点数 转换 不能 类型 | 更新日期: 2023-09-27 18:37:27

我正在做一个简单的程序,用开尔文、摄氏度和华氏度转换温度,但是在使用开尔文做任何事情时我收到此错误:

Cannon implicitly convert type 'double' to 'float'

发生错误的行:

public static float FahrenheitToKelvin(float fahrenheit)
{
    return ((fahrenheit - 32) * 5) / 9 + 273.15;
}

按钮点击:

private void button1_Click(object sender, EventArgs e)
{
    var input = float.Parse(textBox1.Text);
    float FahrenResult = FahrenheitToCelsius(input);
    textBox2.Text = FahrenResult.ToString();
    float KelvinResult = FahrenheitToKelvin(input);
    textBox3.Text = KelvinResult.ToString();
}

以及我正在尝试制作的测试方法:

[TestMethod]
public void fahrenheitToKelvinBoiling()
{
    float fahrenheit = 212F;
    float expected = 373.15F; // TODO: Initialize to an appropriate value
    float actual;
    actual = Form1.FahrenheitToKelvin(fahrenheit);
    Assert.AreEqual(Math.Round(expected, 2), Math.Round(actual, 2));
    // Assert.Inconclusive("Verify the correctness of this test method.");
}

不能将类型“双精度”隐式转换为“浮点数”

试试这个。

    public static float FahrenheitToKelvin(float fahrenheit)
    {
        return ((fahrenheit - 32f) * 5f) / 9f + 273.15f;
    }

这是有效的,因为它改变了编译器将 32 5 等识别为双精度。数字后面的 f 告诉编译器它是一个浮点数。

编译器正在将生成的表达式提升为双精度。我认为它假设那些包含小数部分的数字是双倍的。

不过,您可以将结果值显式转换为浮点数;

或者,您可以尝试将具有小数分隔符的所有常量显式转换为浮点数。

编辑

作为旁注,您是否完全习惯使用浮点数(或双精度)而不是小数?我没有看到您的代码,最终通过调用 ToString() 方法向用户界面显示数据时,将值舍入到一定数量的精度数字(尽管您的单元测试这样做)。

您可能会在浮点数结束时得到一些"丢失"的精度数字,并且它们将使用 ToString() 显示在 UI 上。

我强烈建议:

  1. 使用舍入到一定的小数精度
  2. 将浮点数更改为小数