无法将类型’double’隐式转换为’float’

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

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告诉编译器它是一个浮点数。

编译器将结果表达式提升为double。 我认为它假定那些包含小数部分的数字是双倍的。

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

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

编辑

作为旁注,你是否完全适合使用花车(或双打)而不是小数? 我没有看到你的代码,最终通过调用ToString ()方法将数据显示到用户界面 ,将值四舍五入到一定数量的精确数字(尽管你的unit testing是这样做的)。

您可能会在浮动结束时获得一些“丢失”的精确数字,并且它们将通过使用ToString()显示到UI。

我强烈建议:

  1. 使用舍入到某个小数精度
  2. 将浮点数更改为小数