可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm doing a simple program for converting temperatures with Kelvin, Celsius and Fahrenheit, but I'm getting this error when doing anything with kelvin:
Cannon implicitly convert type 'double' to 'float'
The line the error occurs:
public static float FahrenheitToKelvin(float fahrenheit) { return ((fahrenheit - 32) * 5) / 9 + 273.15; }
The button click:
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(); }
And the test method I'm trying to make:
[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."); }
回答1:
Try this.
public static float FahrenheitToKelvin(float fahrenheit) { return ((fahrenheit - 32f) * 5f) / 9f + 273.15f; }
This works because it changes the compiler from recognizing the 32 5 and so on as doubles. The f after the number tells the compiler it is a float.
回答2:
The compiler is promoting the resulting expression to a double. I think it assumes that those numbers which includes a decimal part are double.
Nevertheless you can explicitly convert the resulting value to a float;
or you can try to explicitly convert all your constants that have a decimal separator to a float.
EDIT
As a side note, are you perfectly comfortable with using a floats (or doubles) instead of decimals? I don't see your code, eventually when displaying data to the user interface by invoking the ToString() method, rounding the value to a certain number of precision digits (although your unit test does it).
You might get some "lost" precision digits at the end of you float and they'll get displayed to the UI by using ToString().
I'd strongly suggest either:
- Use round to a certain decimal precision
- Change the floats to decimals