Math.Pow给出"不能隐式地将类型'double'转换为'float'"错误

Ale*_*ros 2 c# math binary

在这个程序中,我试图创建一个简单的计算器.但是,我似乎无法找到克服上述错误的方法Math.Pow.

namespace BinaryCalc
{
    class Binary
    {
        public static void Main()
        {

        int addition,subtraction;
        float division, multiplication, power, sqrt;

        int x;
        int y;
        x = 10;
        y = 7;

        //Console.WriteLine("Please enter a number for x");
        //string line = Console.ReadLine();
        //int x = int.Parse(line);

        //Console.WriteLine("Please enter a number for y");
        //string line2 = Console.ReadLine();
        //int y = int.Parse(line2);


        addition = (int)x + (int)y;
        subtraction = (int)x - (int)y;
        division = (float)x / (float)y;
        multiplication = (float)x * (float)y;

        power = Math.Pow(x,2);
        sqrt = Math.Sqrt(x);


        Console.WriteLine(" Addition results in {0}", addition);
        Console.WriteLine(" Subtraction results in {0}", subtraction);
        Console.WriteLine(" Division results in {0}", division);
        Console.WriteLine(" Multiplication results in {0}", multiplication);
        Console.WriteLine(" {0} squared results in {0}",x, power);
        Console.WriteLine(" Square root of {0} is: {0}", x, sqrt);

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ing 5

Math.Pow 使用double参数。正如错误所述,没有从to 的隐式转换,因此将结果显式转换为 float:doublefloat

power = (float)Math.Pow(x, 2);
Run Code Online (Sandbox Code Playgroud)

编辑
更正了转换顺序

  • 问题不在于参数,而在于返回值 - 错误表明没有从双精度到浮点的转换,而不是浮点到双精度的转换。 (2认同)

Jon*_*Jon 5

返回值Math.Pow是a double.power程序中的变量是a float,其范围和精度较小.

你应该定义power为a double.