輸入 3 個長方體的長、寬、高,分別計算並輸出其體積和表面積。核心考點:結構體定義、結構體數組作為函數參數、幾何公式應用、浮點數精度。
#include <stdio.h>
struct Box {
float length;
float width;
float height;
};
void volume(struct Box b[], int n);
void surface_area(struct Box b[], int n);
int main() {
struct Box boxes[3];
int i;
for (i = 0; i < 3; i++) {
printf("第 %d 個長方體 (長 寬 高): ", i+1);
scanf("%f %f %f", &boxes[i].length, &boxes[i].width, &boxes[i].height);
}
volume(boxes, 3);
surface_area(boxes, 3);
return 0;
}
void volume(struct Box b[], int n) {
for (int i = 0; i < n; i++) {
float v = b[i].length * b[i].width * b[i].height;
printf("第 %d 體積: %.2f\n", i+1, v);
}
}
void surface_area(struct Box b[], int n) {
for (int i = 0; i < n; i++) {
float sa = 2 * (b[i].length * b[i].width +
b[i].height * b[i].width +
b[i].length * b[i].height);
printf("第 %d 表面積: %.2f\n", i+1, sa);
}
}
// 這三種聲明等價
void volume(struct Box b[], int n);
void volume(struct Box *b, int n);
void volume(struct Box b[3], int n); // 3 被忽略
函數內部無法獲取數組長度,**必須額外傳遞 n**。
// 原代碼 scanf("%f %f %f", ...) 正確
// 若輸入行有逗號:scanf("%f,%f,%f", ...)
// 健壯版:讀行再 sscanf
char line[100];
fgets(line, sizeof(line), stdin);
sscanf(line, "%f %f %f", &l, &w, &h);
長方體 6 個面:
- 底面/頂面:2 × (長 × 寬)
- 前後面:2 × (長 × 高)
- 左右面:2 × (寬 × 高)
總和:2*(l*w + l*h + w*h)
typedef struct {
float l, w, h;
// 方法指針 (模擬成員函數)
float (*volume)(struct Box*);
float (*surface)(struct Box*);
} Box;
float box_volume(Box *b) { return b->l * b->w * b->h; }
float box_surface(Box *b) { return 2*(b->l*b->w + b->l*b->h + b->w*b->h); }
Box create_box(float l, float w, float h) {
Box b = {l, w, h, box_volume, box_surface};
return b;
}
// 使用
Box b = create_box(3, 4, 5);
printf("體積: %.2f, 表面積: %.2f\n", b.volume(&b), b.surface(&b));
bool read_positive_float(const char *prompt, float *out) {
char line[100];
while (1) {
printf("%s", prompt);
if (!fgets(line, sizeof(line), stdin)) return false;
float val;
if (sscanf(line, "%f", &val) == 1 && val > 0) {
*out = val;
return true;
}
printf("請輸入正數!\n");
}
}
// 主循環
for (int i = 0; i < 3; i++) {
read_positive_float("長: ", &boxes[i].length);
read_positive_float("寬: ", &boxes[i].width);
read_positive_float("高: ", &boxes[i].height);
}
長方體計算是結構體數組、函數參數傳遞、幾何公式、浮點格式化的基礎綜合練習。關鍵收穫:
2*(lw + lh + wh) 記住三對面;%.2f 保留兩位小數符合工程習慣;fgets+sscanf 提高健壯性;