编写C++程序,定义重载函数double area (形参表),分别用来求长方形、三角形、正方形、圆的面积,主函数中给定必要的初始数据,分别调用这些函数求面积。
时间: 2023-11-27 14:55:21 浏览: 32
以下是实现上述功能的C++程序:
```cpp
#include <iostream>
using namespace std;
double area(double length, double width) { // 长方形面积函数
return length * width;
}
double area(double bottom, double height, char type) { // 三角形面积函数
if (type == 'r') { // 直角三角形
return 0.5 * bottom * height;
} else { // 等边三角形
return 0.5 * bottom * (height / 2);
}
}
double area(double side) { // 正方形面积函数
return side * side;
}
double area(double radius, int dummy) { // 圆形面积函数
return 3.14159 * radius * radius;
}
int main() {
double length, width, bottom, height, side, radius;
char type;
cout << "请输入长方形的长和宽:" << endl;
cin >> length >> width;
cout << "长方形的面积为:" << area(length, width) << endl;
cout << "请输入三角形的底和高:" << endl;
cin >> bottom >> height;
cout << "请输入三角形的类型(r表示直角三角形,e表示等边三角形):" << endl;
cin >> type;
cout << "三角形的面积为:" << area(bottom, height, type) << endl;
cout << "请输入正方形的边长:" << endl;
cin >> side;
cout << "正方形的面积为:" << area(side) << endl;
cout << "请输入圆的半径:" << endl;
cin >> radius;
cout << "圆的面积为:" << area(radius, 0) << endl;
return 0;
}
```
程序中定义了4个重载函数,分别用来求长方形、三角形、正方形、圆的面积。在主函数中,从用户输入中获取必要的初始数据,并分别调用这些函数求面积。