Following is a book exercise. I develop a program according to instruction in the exercise. I wish to whether my program is correct. Because there are in two places ComputeDiameter(); and ComputeArea(); is coming
Create a class named circle with fields named radius, area, and diameter. Include a constructor that sets the radius to 1. Also include public methods named SetRadius(); GetRadius(); GetDiam(); GetArea(); ComputeDiameter(), which computes a circle's diameter; and ComputeArea(), which computes a circle's area. (The diameter of a circle is
twice its radius; the area is 3.14 multiplied by the square of the radius.)
Create a class named TestCircle whose Main() method declares three circles objects. Using the SetRadius() method, assign a small radius value to one Circle and assign a larger radius value to another Circle. Do not assign a value to the radius of the third circle; instead, retain the value assigned at construction. Call ComputeDiameter() and ComputeArea() for each Circle and display the results.
using System;
namespace ConsoleApplication1
{
class TestCircle
{
static void Main(string[] args)
{
Circle x1 = new Circle();
Circle x2 = new Circle();
Circle x3 = new Circle();
x1.SetRadious(10);
x2.SetRadious(100);
x3.SetRadious(1);
Console.WriteLine("Radious({0}), Diameter({1}), Area({2})", x1.GetRadious(), x1.GetDiameter(), x1.GetArea());
Console.WriteLine("Radious({0}), Diameter({1}), Area({2})", x2.GetRadious(), x2.GetDiameter(), x2.GetArea());
Console.WriteLine("Radious({0}), Diameter({1}), Area({2})", x3.GetRadious(), x3.GetDiameter(), x3.GetArea());
}
}
}
class Circle
{
int radious;
int diameter;
double area;
public Circle()
{
radious = 1;
ComputeDiameter(); //place1
ComputeArea(); //place1
}
public void ComputeDiameter()
{
diameter = 2 * radious;
}
public void ComputeArea()
{
area = 3.14 * radious * radious;
}
public int GetRadious()
{
return this.radious;
}
public void SetRadious(int radious)
{
this.radious = radious;
ComputeDiameter(); //place2
ComputeArea(); //place2
}
public int GetDiameter()
{
return this.diameter;
}
public double GetArea()
{
return this.area;
}
}
Loading
Posted Dec 2, 2011, 4:16 PM
VulpesPosted Dec 2, 2011, 3:50 PM
You're actually told to call ComputeDiameter and ComputerArea on each of the three circles but, for these methods to make any sense, they have to be void because there are GetDiameter and GetArea methods as well which must return values. You've therefore sensibly called these methods instead and called the 'Compute' methods internally.
Another reason why I think it's a silly question is because you only need one field, the radius, to define the essence of a circle. The diameter is always 2 * radius and the area is always pi * radius * radius, so diameter and area are redundant and are occupying memory unnecessarily.
However, you don't really need this line as you can leave it to the constructor to assign the default radius of 1:
x3.SetRadious(1);