Proposed exercise
Create a class "Point3D", to represent a point in 3-D space, with coordinates X, Y and Z. It must contain the following methods:
- MoveTo, which will change the coordinates in which the point is.
- DistanceTo(Point3D p2), to calculate the distance to another point.
- ToString, which will return a string similar to "(2,-7,0)"
- And, of course, getters and setters.
The test program must create an array of 5 points, get data for them, and calculate (and display) the distance from the first point to the remaining four ones.
Output
Solution
using System;
class Point3D
{
private double x, y, z;
public Point3D(double x, double y, double z)
{
MoveTo(x, y, z);
}
public double X
{
get { return x; }
set { x = value; }
}
public double Y
{
get { return y; }
set { y = value; }
}
public double Z
{
get { return z; }
set { z = value; }
}
public void MoveTo(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public double DistanceTo(Point3D p2)
{
return Math.Sqrt( (x - p2.X * x - p2.X) +
(y - p2.Y * y - p2.Y) + (z - p2.Z * z - p2.Z) );
}
public override string ToString()
{
return "(" + x + "-" + y + "-" + z + ")";
}
}
class Test
{
static void Main()
{
Point3D[] points = new Point3D[1];
points[0] = new Point3D(5, 7, -2);
points[1] = new Point3D(-5, -7, -2);
Console.WriteLine("Distance point1 with point2: " + points[0].DistanceTo( points[1]));
}
}