結構體設計
struct Bulk {
float length; // 長
float width; // 寬
float height; // 高
};
核心功能
- 輸入 3 個長方體的長寬高
- 函式
volume() 計算並列印體積 V = lwh
- 函式
area() 計算並列印表面積 S = 2(lw + lh + wh)
- 主程式建立結構體陣列
Bulk b[3],傳遞給函式處理
完整程式碼
#include <stdio.h>
struct Bulk {
float length, width, height;
};
void volume(struct Bulk b[]);
void area(struct Bulk b[]);
int main()
{
struct Bulk boxes[3];
for (int i = 0; i < 3; i++) {
printf("第 %d 個長方體 (長 寬 高): ", i+1);
scanf("%f %f %f", &boxes[i].length, &boxes[i].width, &boxes[i].height);
}
volume(boxes);
area(boxes);
return 0;
}
void volume(struct Bulk b[])
{
for (int i = 0; i < 3; i++) {
float v = b[i].length * b[i].width * b[i].height;
printf("第 %d 體積: %.2f\n", i+1, v);
}
}
void area(struct Bulk b[])
{
for (int i = 0; i < 3; i++) {
float l=b[i].length, w=b[i].width, h=b[i].height;
float s = 2 * (l*w + l*h + w*h);
printf("第 %d 表面積: %.2f\n", i+1, s);
}
}
執行範例
第 1 個長方體 (長 寬 高): 2 3 4
第 2 個長方體 (長 寬 高): 1 1 1
第 3 個長方體 (長 寬 高): 5 2 3
第 1 體積: 24.00
第 2 體積: 1.00
第 3 體積: 30.00
第 1 表面積: 52.00
第 2 表面積: 6.00
第 3 表面積: 62.00
教學重點
- 結構體陣列參數傳遞:實際傳遞首元素位址,函式內可直接修改原資料
- 關注點分離:輸入、體積、表面積三個函式各司其職
- 擴展性:新增長方體只需修改迴圈上限,或改為動態輸入數量
進階:回傳值版本
float volume(struct Bulk b) { return b.length * b.width * b.height; }
float area(struct Bulk b) { ... }
// 主程式迴圈呼叫並自行列印,更彈性