Sunday 5 May 2013

Create a class, Height with two attributes, Feet and Inches. Include the functionality in the class to add two objects of the Height class, as shown in the following example: Height3= Height1 + Height2; Suppose, the object, Height1 contains the value, 5 feet 6 inches and the object, Height2 contains the value, 4 feet 8 inches; then the object Height3 should have the value, 10 feet 2 inches.


using System;
class Height
{
    double feet;
    double inches;
    public Height()
    {
        feet = 0.0;
        inches = 0.0;
    }
    public Height(double feet, double inches)
    {
        this.feet = feet;
        this.inches = inches;
    }
    public static Height operator +(Height d1, Height d2)
    {
        Height h = new Height();
        h.feet = d1.feet + d2.feet;
        h.inches = d1.inches + d2.inches;
        while (h.inches >= 12.0)
        {
            h.feet++;
            h.inches = h.inches - 12.0;
        }
        return h;
    }
    static void Main(string[] args)
    {
        Height d1 = new Height(12.0, 6.8);
        Height d2 = new Height(10, 18.9);
        Height d3 = new Height();
        d3 = d1 + d2;
        Console.WriteLine("feet:" + d3.feet);
        Console.WriteLine("Inches:" + d3.inches);
        Console.ReadLine();
    }
}

1 comment: