Cannot implicitly convert type 'double' to 'float'

I am making a simple temperature conversion program with Kelvin, Celsus and Fahrenheit, but I get this error when I do something with Kelvin:

Cannon implicitly convert type 'double' to 'float'

An error occurs in the line:

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

Button:

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 testing method I'm trying to do:

[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.");
}
+4
source share
2 answers

Try it.

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

This works because it changes the compiler from recognizing 32 5 and so on as doubles. F after the number tells the compiler that it is a float.

+7
source

The compiler promotes the resulting expression in double. I think he assumes that the numbers that include the decimal part double.

float;

, , .

, ( ) ? , , ToString(), ( unit test ).

"" float, ToString().

:

0

All Articles