In: Computer Science
7.24 LAB: Triangle area comparison (classes)
Language: C++
Given class Triangle (in files Triangle.h and Triangle.cpp), complete main() to read and set the base and height of triangle1 and of triangle2, determine which triangle's area is larger, and output that triangle's info, making use of Triangle's relevant member functions.
Ex: If the input is:
3.0 4.0 4.0 5.0
where 3.0 is triangle1's base, 4.0 is triangle1's height, 4.0 is triangle2's base, and 5.0 is triangle2's height, the output is:
Triangle with larger area: Base: 4.00 Height: 5.00 Area: 10.00
Program
/*** Triangle.h ***/
//Triangle.h
#ifndef TRI_H
#define TRI_H
//Triangle class declaration
class Triangle
{
private:
//private data members
float base;
float height;
public:
//constructor
Triangle(float b=0,float h=0);
//accessors functions
float getBase();
float getHeight();
//mutators functions
void setBase(float b);
void setheight(float h);
//calculate area
float getArea();
//print the triangle
void print();
};
#endif //TRI_H
/*** Triangle.cpp ***/
//Triangle.cpp
#include<iostream>
#include<iomanip>
#include "Triangle.h"
using namespace std;
//parameterized constructor
Triangle::Triangle(float b,float h)
{
base = b;
height = h;
}
/* accessors functions */
//function to return base
float Triangle::getBase()
{
return base;
}
//function to return height
float Triangle::getHeight()
{
return height;
}
/*mutators functions*/
//function to set base
void Triangle::setBase(float b)
{
base = b;
}
//function to set height
void Triangle::setheight(float h)
{
height = h;
}
//calculate area
float Triangle::getArea()
{
return (0.5*base*height);
}
//print the triangle
void Triangle::print()
{
cout<<fixed<<setprecision(2);
cout<<"Base: " <<base<<endl;
cout<<"Height: "<<height<<endl;
cout<<"Area: "<<getArea()<<endl;
}
/*** main.cpp ***/
#include <iostream>
#include"triangle.h"
using namespace std;
//main function
int main()
{
Triangle t1, t2;
float base, height;
cout<<"Enter base: ";
cin >>base;
cout<<"Enter height: ";
cin >>height;
t1.setBase(base);
t1.setheight(height);
cout<<"Enter base: ";
cin >>base;
cout<<"Enter height: ";
cin >>height;
t2.setBase(base);
t2.setheight(height);
cout<<"Triangle with larger area:"<<endl;
if(t1.getArea()>t2.getArea())
t1.print();
else
t2.print();
return 0;
}
Output:
Solving your question and
helping you to well understand it is my focus. So if you face any
difficulties regarding this please let me know through the
comments. I will try my best to assist you. However if you are
satisfied with the answer please don't forget to give your
feedback. Your feedback is very precious to us, so don't give
negative feedback without showing proper reason.
Always avoid copying from existing answers to avoid
plagiarism.
Thank you.