定义盒子 Box 类,要求具有以下成员:可设置盒子形状;可计算盒子体积; 可计算盒子的表面积。 c++
时间: 2024-05-13 13:15:26 浏览: 26
下面是一个简单的实现:
```c
#include <stdio.h>
typedef struct {
int length;
int width;
int height;
} Box;
void set_shape(Box *box, int length, int width, int height) {
box->length = length;
box->width = width;
box->height = height;
}
int calc_volume(Box box) {
return box.length * box.width * box.height;
}
int calc_surface_area(Box box) {
return 2 * (box.length * box.width + box.length * box.height + box.width * box.height);
}
int main() {
Box box;
set_shape(&box, 2, 3, 4);
printf("The volume of the box is %d\n", calc_volume(box));
printf("The surface area of the box is %d\n", calc_surface_area(box));
return 0;
}
```
在这个示例中,我们使用结构体 `Box` 来表示盒子,其中包含长、宽、高三个成员变量。我们定义了三个函数,分别是 `set_shape`、`calc_volume` 和 `calc_surface_area`,来设置盒子形状、计算盒子体积和计算盒子表面积。在 `main` 函数中,我们声明了一个 `Box` 实例 `box`,并通过 `set_shape` 函数设置了其形状为长为2、宽为3、高为4。然后我们使用 `calc_volume` 和 `calc_surface_area` 函数计算了盒子的体积和表面积,并将结果打印出来。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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://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)