Cannot implicitly convert type 'double' to 'float'

后端 未结 2 1772
旧时难觅i
旧时难觅i 2020-12-19 04:10

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:

Can         


        
相关标签:
2条回答
  • 2020-12-19 04:18

    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.

    0 讨论(0)
  • 2020-12-19 04:35

    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:

    1. Use round to a certain decimal precision
    2. Change the floats to decimals
    0 讨论(0)
提交回复
热议问题