无法隐式转换类型'双'到'浮动' [英] Cannot implicitly convert type 'double' to 'float'

查看:145
本文介绍了无法隐式转换类型'双'到'浮动'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个简单的程序与开尔文,摄氏和华氏温度转换,但这样做有什么开尔文时,我得到这个错误:

 炮隐式转换类型'双'到'浮动'

发生错误的行:

 公共静态浮动FahrenheitToKelvin(华氏浮动)
{
    回报((华氏 - 32)* 5)/ 9 + 273.15;
}

按钮点击:

 私人无效的button1_Click(对象发件人,EventArgs的发送)
{
    VAR输入= float.Parse(textBox1.Text);
    浮FahrenResult = FahrenheitToCelsius(输入);
    textBox2.Text = FahrenResult.ToString();
    浮KelvinR​​esult = FahrenheitToKelvin(输入);
    textBox3.Text = KelvinR​​esult.ToString();
}

和测试方法,我试图让:

  [TestMethod的]
公共无效fahrenheitToKelvinBoiling()
{
    华氏浮= 212F;
    浮预计= 373.15F; // TODO:初始化为适当的值
    浮实际;
    实际= Form1.FahrenheitToKelvin(华氏度);
    Assert.AreEqual(Math.Round(预期,2),Math.Round(实际,2));
    // Assert.Inconclusive(验证这种测试方法的正确性。);
}


解决方案

试试这个。

 公共静态浮动FahrenheitToKelvin(华氏浮动)
    {
        返回((华氏 - 32F)* 1006米)/ 9F + 273.15f;
    }

这工作,因为它改变了从等为双打承认32 5和编译器。在数字后在F告诉编译器它是一个浮动。

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.");
}

解决方案

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.

这篇关于无法隐式转换类型'双'到'浮动'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆