编写 C++程序, 定义重载函数 double area(形参表),分别用来求长方 (形参表),分别用来求长方 (形参表),分别用来求长方 形、三角正方圆的面积,主函数中给定必要初始据分别调用这些函数求面积
时间: 2024-02-21 13:59:01 浏览: 64
C++编写计算三角形、正方形和圆形面积程序
5星 · 资源好评率100%
好的,以下是一个示例程序:
```c++
#include <iostream>
using namespace std;
double area(double length, double width) {
return length * width;
}
double area(double side) {
return side * side;
}
double area(double base, double height, string type) {
if (type == "triangle") {
return 0.5 * base * height;
} else if (type == "circle") {
return 3.14159 * base * base / 4;
}
}
int main() {
double length, width, side, base, height;
cout << "Please enter the length and width of the rectangle: ";
cin >> length >> width;
cout << "The area of the rectangle is: " << area(length, width) << endl;
cout << "Please enter the side length of the square: ";
cin >> side;
cout << "The area of the square is: " << area(side) << endl;
cout << "Please enter the base and height of the shape (triangle or circle): ";
cin >> base >> height;
cout << "Please enter the type of the shape (triangle or circle): ";
string type;
cin >> type;
cout << "The area of the " << type << " is: " << area(base, height, type) << endl;
return 0;
}
```
该程序中定义了三个重载函数 `area`,用于计算长方形、正方形、三角形和圆形的面积。主函数中通过用户的输入调用这些函数并输出计算结果。注意,在计算三角形和圆形的面积时,需要额外传入一个字符串类型的参数 `type`,用于判断计算的是三角形还是圆形。
阅读全文