首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 矩形 ADT 實現:周長與面積計算函數完整代碼

     編輯:程式設計綜合問答

題目要求

基於給定的 Rect 結構體和 InitRect 初始化函數,補全求周長 getround 和面積 getarea 操作。

完整可運行代碼

#include <iostream>
using namespace std;

struct Rect {
    double length;
    double width;
};

// 聲明
void InitRect(Rect &R, double l, double w);
double getarea(Rect &R);
double getround(Rect &R);

int main() {
    Rect my_rect;
    double Length, Width, Circ, Area;
    
    cout << "Input length, width: " << endl;
    cin >> Length >> Width;
    
    InitRect(my_rect, Length, Width);
    
    Area = getarea(my_rect);
    Circ = getround(my_rect);
    
    cout << "Area = " << Area << endl;
    cout << "Circumference = " << Circ << endl;
    
    return 0;
}

// 初始化
void InitRect(Rect &R, double l, double w) {
    R.length = l;
    R.width = w;
}

// 面積
double getarea(Rect &R) {
    return R.length * R.width;
}

// 周長
double getround(Rect &R) {
    return 2 * (R.length + R.width);
}

關鍵點解析

  • 引用參數:Rect &R 避免結構體拷貝,且允許函數修改原對象(初始化時需要)。
  • 職責單一:每個函數只做一件事(初始化、算面積、算周長),符合高內聚原則。
  • 命名規範:getarea/getround 動詞開頭,語義清晰。

擴展練習

  1. 添加 bool isSquare(Rect &R) 判斷是否為正方形。
  2. 重載 operator<< 直接輸出矩形信息:cout << my_rect;。
  3. 改用 class 封裝,私有成員,提供構造函數、getter/setter。
  4. 處理輸入異常:長寬必須 > 0,否則拋出異常或提示重輸。

面試延伸:C++ 結構體 vs 類

結構體 struct 默認成員 public,類 class 默認 private;繼承默認訪問權限同理。本質上無區別,語義上 struct 傾向純數據聚合,class 傾向行為封裝。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved