利用C++函数重载的功能,编写两个重裁函数分别实现对圆形和矩阵求面积的功能,编写main函数读入一个圆的半径和一个矩阵的长,宽数据,调用函数area分别输出它们的面积,输入输出如下: 5 4 3 78.5,12
时间: 2024-02-17 22:05:35 浏览: 24
好的,以下是代码实现:
```c++
#include <iostream>
using namespace std;
const double PI = 3.14159265358979323846; // 定义圆周率常量
// 计算圆形面积的函数重载
double area(double r) {
return PI * r * r;
}
// 计算矩形面积的函数重载
double area(double length, double width) {
return length * width;
}
int main() {
double r, l, w;
cin >> r >> l >> w;
double circleArea = area(r);
double rectangleArea = area(l, w);
cout << circleArea << " " << rectangleArea << endl;
return 0;
}
```
运行结果:
输入:
```
5 4 3
```
输出:
```
78.5398 12
```
相关问题
利用C++函数重载的功能,编写两个重裁函数Abs分别实现对整数和浮点数求绝对值的功能,编写main函数读入1个int数据和1个double数据,调用函数fun分别输出它们的绝对值
好的,这是代码实现:
```c++
#include <iostream>
using namespace std;
int Abs(int x) {
return x < 0 ? -x : x;
}
double Abs(double x) {
return x < 0 ? -x : x;
}
int main() {
int a;
double b;
cin >> a >> b;
cout << Abs(a) << endl;
cout << Abs(b) << endl;
return 0;
}
```
函数重载的实现原理是根据函数名相同但参数类型或参数个数不同来区分不同的函数。在本题中,我们定义了两个名为 `Abs` 的函数,一个参数类型为 `int`,另一个参数类型为 `double`,分别实现对整数和浮点数求绝对值的功能。在 `main` 函数中,我们读入一个 `int` 和一个 `double` 类型的数,分别调用 `Abs` 函数并输出结果。
用c++编写一个函数分别求三角形、矩形,圆形的图形面积
好的,以下是用C++编写的函数分别求三角形、矩形和圆形的面积:
```c++
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159265358979323846;
double triangleArea(double base, double height) {
return 0.5 * base * height;
}
double rectangleArea(double length, double width) {
return length * width;
}
double circleArea(double radius) {
return PI * pow(radius, 2);
}
int main() {
double base, height, length, width, radius;
cout << "Enter base and height of triangle: ";
cin >> base >> height;
cout << "Area of triangle: " << triangleArea(base, height) << endl;
cout << "Enter length and width of rectangle: ";
cin >> length >> width;
cout << "Area of rectangle: " << rectangleArea(length, width) << endl;
cout << "Enter radius of circle: ";
cin >> radius;
cout << "Area of circle: " << circleArea(radius) << endl;
return 0;
}
```
希望这个函数可以帮助你计算图形的面积。