定义一个rectangle类,有两个属性length和width,即默认值均为1,完成以下内容:
1.定义两个成员原函数,分别计算长方形的周长和面积
2.为length和width属性定义设置set函数和get函数
3.使用set函数验证两个属性值均在0-20之间
4.输出给定长度和宽度后长方形的周长和面积
#include <stdio.h>
// 定义rectangle类
typedef struct {
int length; // 长
int width; // 宽
} Rectangle;
// 计算周长
int getPerimeter(Rectangle rect) {
return 2 * (rect.length + rect.width);
}
// 计算面积
int getArea(Rectangle rect) {
return rect.length * rect.width;
}
// 设置 length 属性值
void setLength(Rectangle *rect, int length) {
if (length >= 0 && length <= 20) {
rect->length = length;
} else {
printf("Error: length should be between 0 and 20\n");
}
}
// 获取 length 属性值
int getLength(Rectangle rect) {
return rect.length;
}
// 设置 width 属性值
void setWidth(Rectangle *rect, int width) {
if (width >= 0 && width <= 20) {
rect->width = width;
} else {
printf("Error: width should be between 0 and 20\n");
}
}
// 获取 width 属性值
int getWidth(Rectangle rect) {
return rect.width;
}
int main() {
Rectangle rect;
rect.length = 1;
rect.width = 1;
// 设置属性值并验证
setLength(&rect, 5);
setWidth(&rect, 10);
// 输出周长和面积
printf("The perimeter of rectangle is: %d\n", getPerimeter(rect));
printf("The area of rectangle is: %d\n", getArea(rect));
return 0;
}