I have this code and I am trying to calculate the area and circumference of the circle. I have tried debugging and I can see that the radius
was passed but the area
and circumference
is not, it's always 0.
using System;
class Circle{
double radius;
double area;
double circumference;
public double Radius{set{radius = value;}}
public double Area{set{area=value;}}
public double Circumference{set{circumference=value;}}
public Circle(double radius){
this.radius = radius;
area=0;
circumference=0;
}
void CalculateArea(){
area=Math.PI*Math.Pow(radius,2);
}
void CalculateCircumference(){
circumference = 2*Math.PI*radius;
}
public void DisplayArea(){
System.Console.WriteLine("Area is {0}",area);
}
public void DisplayCircumference(){
System.Console.WriteLine("Circumference is {0}",circumference);
}
}
class TestCircle{
public static void Main(string[] args)
{
System.Console.WriteLine("Enter radius: ");
double radius=Convert.ToDouble(Console.ReadLine());
Circle theCircle = new Circle(radius);
theCircle.DisplayArea();
theCircle.DisplayCircumference();
}
}
this is the output
Enter radius:
3
Area is 0
Circumference is 0
CodePudding user response:
You have a very strange design: set only Radius
(once set I can't read it), editable (both get
and set
) Area
: one
can easily assign -1.0
to it...
Let's redesign it; we have Circle
class with three properties only:
class Circle{
// Radius, the man property we can
// - read it (get)
// - assign it, but let it be just once (so set is private)
public double Radius {get; private set;}
// Area, which we can just read (get, no set)
public double Area => Math.PI * Radius * Radius;
// Circumference, which we can just read (get, no set)
public double Circumference => 2 * Math.PI * Radius;
public Circle(double radius) {
Radius = radius;
}
public void DisplayArea(){
System.Console.WriteLine($"Area is {Area}");
}
public void DisplayCircumference(){
System.Console.WriteLine($"Circumference is {Circumference}");
}
}