编写一个c++程序,设计一个函数rect,要求该函数能计算矩形面积
时间: 2023-05-29 22:06:29 浏览: 97
#include <stdio.h>
int rect(int length, int width) {
int area = length * width;
return area;
}
int main() {
int length, width;
printf("请输入矩形的长度和宽度:\n");
scanf("%d%d", &length, &width);
printf("矩形的面积为:%d\n", rect(length, width));
return 0;
}
相关问题
用C++编写一个程序来计算矩形的面积。
一个简单的 C++ 程序可以使用以下代码来计算矩形的面积:
```
#include <iostream>
using namespace std;
int main() {
double width, height;
cout << "Enter the width of the rectangle: ";
cin >> width;
cout << "Enter the height of the rectangle: ";
cin >> height;
double area = width * height;
cout << "The area of the rectangle is: " << area << endl;
return 0;
}
```
这个程序先从用户处读取矩形的宽和高,然后计算矩形的面积并输出结果。
如果要编写一个面向对象的程序来计算矩形的面积,可以创建一个 Rectangle 类,其中包含成员变量 width 和 height,以及成员函数 getArea(),如下所示:
```
class Rectangle {
private:
double width;
double height;
public:
Rectangle(double w, double h) {
width = w;
height = h;
}
double getArea() {
return width * height;
}
};
```
然后在 main 函数中创建一个 Rectangle 对象,调用它的 getArea() 函数来计算矩形的面积,如下所示:
```
int main() {
double width, height;
cout << "Enter the width of the rectangle: ";
cin >> width;
cout << "Enter the height of the rectangle: ";
cin >> height;
Rectangle rect(width, height);
double area = rect.getArea();
cout << "The area of the rectangle is: " << area << endl;
return 0;
}
```
输出结果与之前的程序相同。
用C++编写一个面向对象的程序来计算矩形的面积。
一个简单的面向对象的矩形类可以包含以下成员变量和成员函数:
```
class Rectangle {
private:
double width; // 矩形的宽
double height; // 矩形的高
public:
Rectangle(double w, double h); // 构造函数
double getArea(); // 计算矩形面积
};
```
其中,构造函数用于初始化矩形的宽和高,getArea() 函数用于计算矩形的面积。类的实现如下:
```
Rectangle::Rectangle(double w, double h) {
width = w;
height = h;
}
double Rectangle::getArea() {
return width * height;
}
```
然后可以在 main 函数中创建一个 Rectangle 对象,调用它的 getArea() 函数来计算矩形的面积,如下所示:
```
int main() {
Rectangle rect(3.0, 4.0); // 创建一个宽为 3,高为 4 的矩形对象
double area = rect.getArea();
cout << "The area of the rectangle is: " << area << endl;
return 0;
}
```
输出结果为:
```
The area of the rectangle is: 12
```