开发者

Math.Pow gives "Cannot implicitly convert type 'double' to 'float' " error

In this program I am trying to create a simple calculator. However, I can't seem to find a way to overcome the aforementioned error when reaching the Math.Pow line.

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(" Multi开发者_运维知识库plication results in {0}", multiplication);
        Console.WriteLine(" {0} squared results in {0}",x, power);
        Console.WriteLine(" Square root of {0} is: {0}", x, sqrt);

        }
    }
}


Math.Pow uses a double argument. As the error says, there is no implicit conversion from double to float, so convert the result explicitly to float:

power = (float)Math.Pow(x, 2);

EDIT
corrected the conversion order


The return value of Math.Pow is a double. The variable power in your program is a float, which has a smaller range and accuracy.

You should define power to be a double.


Use double instead of float for your variables.

The float data type has quite limited precision, so the rounding errors (that are always present in floating point arithmetics) are relatively large.

The reason that you see the wrong result of the square and square root, is that you never show the result at all. Change one of the {0} in each format string into {1}:

Console.WriteLine(" {0} squared results in {1}",x, power);
Console.WriteLine(" Square root of {0} is: {1}", x, sqrt);


You can try explicitly casting the results of Math.Pow to float as such:

power = (float) Math.Pow(x, 2);

You can also use float's TryParse method to try and parse the result of Math.Pow:

float.TryParse(Math.Pow(x, 2).ToString(), out power);

Also, you might want to change the format string parameter numbers on the last two Console.WriteLine method calls. They should read like this:

Console.WriteLine(" {0} squared results in {1}",x, power);
Console.WriteLine(" Square root of {0} is: {1}", x, sqrt);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜