In the following block of code when I try to print the triangle's area why am I always getting the answer to be 1. I can't seem to figure out what the problem is here. You might want to copy-paste this code into your system.
I want to calculate the area of rectangle and triangle by inheriting them as derived classes from the base class shape. I have tried to use a switch case to create a neat menu. But for some reason, whenever I try to calculate the area of the triangle it always gives me the value to be 1. I can't figure out what the problem is. Can anyone help?
/**
* @file L6W9.cpp
* @author calculates area using base class and virtual funcitons
* @brief
* @version 0.1
* @date 2022-03-16
*
* @copyright Copyright (c) 2022
*
*/
#include<iostream>
#include<cmath>
using namespace std;
class shape{
public:
double side_one;
double side_two;
shape(){}
shape(double a, double b ){
side_one = a;
side_two = b;
}
void set_data(double x, double y)
{
side_one = x;
side_two = y;
}
virtual void display_area(){
}
void display(){
cout<<"Side one: "<<side_one<<endl<<"Side two: "<<side_two<<endl;
}
};
class triangle: public shape{
public:
double side_three;
triangle(){}
void set_data(double x, double y ,double z ){
shape:: set_data(x,y);
side_three = z;
}
void display_area(){
double s = (side_one+ side_two + side_three)/2;
double x = s*(s-side_one)*(s-side_two)*(s-side_three);
double triangle_area = pow(s*x,1/2);
cout<<"The area of the triangle is: "<<triangle_area<<" "<<"squared units"<<endl;
}
void display(){
cout<<"Length of first side : "<<side_one<<"units"<<endl;
cout<<"Length of second side : "<<side_two<<"units"<<endl;
cout<<"Length of third side : "<<side_three<<"units"<<endl;
}
};
class rectangle : public shape{
public:
rectangle(){}
void display_area()
{
double rect_area = side_one *side_two; // length*breadth
cout<<"The area of the rectangle is: "<<rect_area <<" "<<"sqaured units"<<endl<<endl;
}
void display(){
cout<<"Length of the rectangle is: "<<side_one<<" "<<"units"<<endl;
cout<<"Breadth of the rectangle is "<<side_two<<" "<<"units"<<endl;
}
};
void menu(){
cout<<"**********************************************"<<endl;
cout<<"Choose betweeen rectangle and triangle"<<endl;
cout<<"Rectangle: 1"<<endl;
cout<<"Trianlge: 2"<<endl;
cout<<"Quit: 0 "<<endl;
cout<<"***********************************************"<<endl;
}
int main()
{
rectangle r1;
triangle t1;
int choice;
do{
menu();
cin>>choice;
switch(choice){
case 0 :
break;
case 1:
cout<<"You have chosen: Rectangle"<<endl;
double a, b;
cout<<"Lenght: ";
cin>>a;
cout<<"Breadth: ";
cin>>b;
r1.set_data(a,b);
r1.display();
r1.display_area();
break;
case 2:
cout<<"You have chosen: Triangle"<<endl;
double c,d,e;
cout<<"Side one: ";
cin>>c;
cout<<"Side two: ";
cin>>d;
cout<<"Side three: ";
cin>>e;
t1.set_data(c,d,e);
t1.display();
t1.display_area();
break;
default:
cout<<"Invalid Output"<<endl;
break;
}
}
while (choice!=0);
return 0;
}