Lab 9 Class and Objects

advertisement
CS2311 Computer Programming
Lab 9
Class and Objects
Q1. Download triangle.cpp.
Define a class for triangles. The following private members should be defined: (i) side1,
side2, side3: double representing the lengths of three sides of the triangle (ii) name: a
character ID, e.g. ‘T’, of the triangle.
Write a constructor which initializes the three sides and name members accordingly.
Also let’s create access functions to access the private members. (e.g.
Triangle::setLengths(double, double, double) )
Finally, define a member function to return the area of the Triangle
double Rectangle::getArea();
You may use the Heron’s Formula to calculate the area of a triangle:
Area = sqrt(s*(s-a)*(s-b)*(s-c)), where s=(a+b+c)/2.
You need to include <cmath> library to use the sqrt() function.
In the main function, declare a Triangle x. The program should let the user input the ID, and
lengths x. The getArea() member function should be called to compute its area. The
program prints the name, length, height of the rectangle and its area (to 2 decimal places).
Sample input and output:
3 4 5 T
The rectangle T has an area of 6.00.
Q2. Extend the program in Q1 to define a non-member function larger(), which accepts
two Triangle objects as input. The function should return a Boolean to specify whether the
first Triangle has a larger area than the second one or not. (Also return false if their areas are
identical.)
You may use the following function to test your program:
void testLargerTriangle(){
Triangle x(10,15,20,'X');
Triangle y, max;
y.setLengths(10,10,10);
y.setName('Y');
if (larger(x,y))
max=x;
else
max=y;
cout<<"The triangle " << max.getName()
<< " has a larger area.\n";
}
-1-
CS2311 Computer Programming
Q3. Modify the program such that the program defines an array of triangles:
Triangle arr[10];
The program should let the user input the name and lengths and of n triangles (where n is
an integer input by the user and 0<n<=10) and store them in the array. The program should
print the name of the triangle with the largest area (if there are more than one triangles with
the same maximum area, print the first one in the original order that they are defined).
Enter the number of
Enter triangle 1: 3
Enter triangle 2: 2
Maximum triangle:
Triangle 1, name=A,
triangles: 2
4 5 A
3 4 B
area is 6.00.
-2-
Download