Write a program that uses a class rectangle in a separate header file. The class
ID: 3567062 • Letter: W
Question
Write a program that uses a class rectangle in a separate header file.
The class has data members for length, width, area, and perimeter. The length and width can be set by the user, but the area and perimeter can not be set by the user (their values depend on the values of length and width). Include 2 other member functions that separately calculates the perimeter and area of the rectangle. Let the user be able to separately get the value of all 4 data fields. Include a constructor, that does not take any arguments, but initializes all the data fields, the length and width to 1, and the area and perimeter calculated as in the two calculate functions.
The main program file will declare a rectangle object, call the member functions to calculate the perimeter and area, and then get and print out the results.
Use the following ex5-1.cpp and create the corresponding rectangle5-1.h header file.
#include<iostream>
#include"rectangle5-1.h"
using namespace std;
void main()
{
rectangle51 r; // write constructor
float len, wid;
cout << "Enter length: ";
cin >> len;
r.setlength(len); // write functions
cout << "Enter width: ";
cin >> wid;
r.setwidth(wid);
r.calcarea();
r.calcperimeter();
cout << "Rectangle's length = " << r.getlength() << endl;
cout << "Rectangle's width = " << r.getwidth() << endl;
cout << "Rectangle's area = " << r.getarea() << endl;
cout << "Rectangle's perimeter = " << r.getperimeter() << endl;
}
Explanation / Answer
class rectangle51
{
public:
float length;
float width;
float area;
float perimeter;
void setlength(float len)
{
length = len;
}
void setwidth(float wid)
{
width = wid;
}
void calcarea()
{
area = (length * width);
}
void calcperimeter()
{
perimeter = (2*(length + width));
}
float getlength()
{
return length;
}
float getwidth()
{
return width;
}
float getarea()
{
return area;
}
float getperimeter()
{
return perimeter;
}
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.