首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言結構體應用:長方體體積與表面積計算(結構體數組傳遞)

     編輯:關於C語言

問題描述

輸入 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);
    }
}

關鍵技術點

1. 結構體數組參數退化為指針


// 這三種聲明等價
void volume(struct Box b[], int n);
void volume(struct Box *b, int n);
void volume(struct Box b[3], int n);  // 3 被忽略

函數內部無法獲取數組長度,**必須額外傳遞 n**。

2. 浮點數輸入掃描集


// 原代碼 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);

3. 表面積公式拆解

長方體 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);
}

總結

長方體計算是結構體數組、函數參數傳遞、幾何公式、浮點格式化的基礎綜合練習。關鍵收穫:

  • 結構體數組傳遞**必須額外傳長度 n**;
  • 表面積公式 2*(lw + lh + wh) 記住三對面;
  • 輸出 %.2f 保留兩位小數符合工程習慣;
  • 輸入驗證 (正數檢查) 和行讀取 fgets+sscanf 提高健壯性;
  • 方法指針封裝展示 C 語言模擬面向對象的可能性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved