C语言定义矩形类类内有数据成员和求面积和周长以及给数据成员赋初值的函数,在主函数中定义对象并赋值,求出该对象的面积和周长。
时间: 2024-05-03 18:20:27 浏览: 17
您好,关于您的问题,以下是一份代码示例:
```c
#include <stdio.h>
typedef struct {
float width;
float height;
} Rectangle;
void initRectangle(Rectangle* rect, float width, float height) {
rect->width = width;
rect->height = height;
}
float getArea(Rectangle rect) {
return rect.width * rect.height;
}
float getPerimeter(Rectangle rect) {
return 2 * (rect.width + rect.height);
}
int main() {
Rectangle rect;
initRectangle(&rect, 5, 10);
printf("The area of the rectangle is %.2f\n", getArea(rect));
printf("The perimeter of the rectangle is %.2f\n", getPerimeter(rect));
return 0;
}
```
代码中定义了一个矩形类,包含长和宽两个数据成员,以及一个初始化函数 `initRectangle` 用于给数据成员赋初值,和两个计算面积和周长的函数 `getArea` 和 `getPerimeter`。在 `main` 函数中,先定义一个矩形对象 `rect`,然后调用初始化函数初始化对象,并通过调用面积和周长计算函数计算出对象的面积和周长,最后输出结果。
希望这能够解答您的问题。如果您有更多的问题,可以继续提出,我会尽力回答。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)