Why am I getting a value of zero for my circle?

微笑、不失礼 提交于 2019-12-07 14:33:35

问题


Here is my Circle class code.

class Circle
{
    private double radius;
    private double area;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public double Area
    {
        set { area = Math.PI * Math.Pow(radius, 2); }
        get { return area; }

    }
}

This is test code.

    Circle circle1 = new Circle(3);

    MessageBox.Show("Circle 1 Area: " + circle1.Area);

So for some reason, when I use the MessageBox.Show(), it seems to give me values of zero instead. I gave the circle a value of 3 so shouldn't my constructor set the value of the radius that?


回答1:


Because you haven't ever called the setter on Area. Perhaps you want something like this instead?

class Circle
{
    private double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public double Area
    {
        get { return Math.PI * Math.Pow(radius, 2); }    
    }
}

This will compute the Area every time it is requested.




回答2:


Your Area property should be:

public double Area
{
    get { return Math.PI * Math.Pow(radius, 2); }
}

and you don't need the area field.




回答3:


I'm not sure you need a set in this instance (You didn't use it)

try

    get { return  Math.PI * Math.Pow(radius, 2); }


来源:https://stackoverflow.com/questions/19844974/why-am-i-getting-a-value-of-zero-for-my-circle

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