Introduce Parameter Object C语言示例
时间: 2023-08-15 15:33:34 浏览: 153
假设有一个名为“图形”的结构体,该结构体包含三个属性:形状(shape)、半径(radius)和边长(length)。我们现在需要编写一个名为“计算图形面积”的函数,计算图形的面积。使用引入参数对象重构手法,代码如下:
```c
// 原始代码
struct Shape {
char* shape;
double radius;
double length;
};
double calculate_area(struct Shape shape) {
if (strcmp(shape.shape, "圆") == 0) {
return 3.14 * shape.radius * shape.radius;
} else if (strcmp(shape.shape, "正方形") == 0) {
return shape.length * shape.length;
} else {
return 0;
}
}
// 重构后的代码
struct Shape {
char* shape;
double radius;
double length;
};
double calculate_circle_area(double radius) {
return 3.14 * radius * radius;
}
double calculate_square_area(double length) {
return length * length;
}
double calculate_area(struct Shape shape) {
if (strcmp(shape.shape, "圆") == 0) {
return calculate_circle_area(shape.radius);
} else if (strcmp(shape.shape, "正方形") == 0) {
return calculate_square_area(shape.length);
} else {
return 0;
}
}
int main() {
struct Shape circle = { "圆", 5, 0 };
double area = calculate_area(circle);
printf("圆的面积为
阅读全文