面试题答案
一键面试#include <stdio.h>
// 定义图形类型枚举
typedef enum {
CIRCLE,
RECTANGLE,
TRIANGLE
} ShapeType;
// 定义结构体表示图形
typedef struct {
ShapeType type;
union {
float radius; // 圆形半径
struct {
float length; // 矩形长度
float width; // 矩形宽度
} rectangle;
struct {
float base; // 三角形底
float height; // 三角形高
} triangle;
} params;
} Shape;
// 宏定义计算圆形面积
#define CIRCLE_AREA(radius) ((radius) * (radius) * 3.14159f)
// 宏定义计算矩形面积
#define RECTANGLE_AREA(length, width) ((length) * (width))
// 宏定义计算三角形面积
#define TRIANGLE_AREA(base, height) (0.5f * (base) * (height))
// 计算总面积函数
float calculateTotalArea(Shape shapes[], int count) {
float totalArea = 0;
for (int i = 0; i < count; i++) {
switch (shapes[i].type) {
case CIRCLE:
totalArea += CIRCLE_AREA(shapes[i].params.radius);
break;
case RECTANGLE:
totalArea += RECTANGLE_AREA(shapes[i].params.rectangle.length, shapes[i].params.rectangle.width);
break;
case TRIANGLE:
totalArea += TRIANGLE_AREA(shapes[i].params.triangle.base, shapes[i].params.triangle.height);
break;
}
}
return totalArea;
}
你可以这样调用这个函数:
int main() {
Shape shapes[] = {
{CIRCLE, {1.0f}},
{RECTANGLE, {{2.0f, 3.0f}}},
{TRIANGLE, {{4.0f, 5.0f}}}
};
int count = sizeof(shapes) / sizeof(shapes[0]);
float totalArea = calculateTotalArea(shapes, count);
printf("Total area: %f\n", totalArea);
return 0;
}