Why am I getting the error implicitly converting type double to an int?

老子叫甜甜 提交于 2020-04-17 22:17:11

问题


How do I fix the error "Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?). I don't see where I am changing an int to a double. Here's the following code I am working with:

namespace Chapter_9
{
    class Program
    {
        static void Main(string[] args)
        {
            Circle create = new Circle();
            create.SetRadius(2);
            WriteLine("Radius = {0}", create.GetRadius());
            WriteLine("Diameter = {0}", create.GetDiameter());
            WriteLine("Area = {0}", create.GetArea());
        }
    }
    class Circle
    {
        private int Radius;
        private readonly int Diameter;
        private readonly double Area;

        public Circle()
        {
            CircleRadius = 1;
        }
        public int CircleRadius { get; set; }
        public int GetRadius()
        {
            return Radius;
        }
        public void SetRadius(int radius)
        {
            Radius = radius;
        }
        public int GetDiameter()
        {
            int Diameter = Radius * 2;
            return Diameter;
        }
        public int GetArea()
        {
            double Area = Radius * Radius * Math.PI;
            return Area; <--------- !!!!ERROR IS HERE!!!
        }
    }
}

回答1:


As you said, your main problem is that you want precise decimal calculation over integers. Yet your return type of public int GetArea() is int. To fix your immediate problem - just change its type to double and that will be it!

However there are a couple of other improvements you can make. First of all - you have public int CircleRadius { get; set; } that is not used. Then, as @Enigmativity said you are writing this in Java style. Use autoproperties a bit more, it will be much easier. And take note of your fields - you declared them but have not used...

Here is a cleaned up class:

class Circle
{
    public double Radius {get; set;}
    public double Diameter 
    { 
        get 
        {
            return Radius * 2;
        }
    }
    public double Area
    { 
        get 
        {
            return Radius * Radius * Math.PI;
        }
    }

    public Circle()
    {
        this.Radius = 1;
    }
}

And your main would be

static void Main(string[] args)
{
    Circle create = new Circle();
    create.Radius = 2;
    WriteLine("Radius = {0}", create.Radius);
    WriteLine("Diameter = {0}", create.Diameter);
    WriteLine("Area = {0}", create.Area);
}



回答2:


It looks like you intended to return a double, but you declared your method as returning int.



来源:https://stackoverflow.com/questions/60940739/why-am-i-getting-the-error-implicitly-converting-type-double-to-an-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!