阿摩線上測驗 登入

申論題資訊

試卷:97年 - 097年地方4等_資訊處理#32437
科目:程式設計
年份:97年
排序:0

申論題內容

⑵定義 volume ()函數,用來計算 CBox 物件的體積。(7 分)

詳解 (共 1 筆)

詳解 提供者:hchungw
class CBox {
public:
    int length; // 長度
    int width;  // 寬度
    int height; // 高度
    // 構造函數
    CBox(int l, int w, int h) : length(l), width(w), height(h) {}
    // 預設構造函數
    CBox() : length(0), width(0), height(0) {}
    // 成員函數,用來計算體積
    int volume() {
        return length * width * height;
    }
};
volume() 函數解釋
函數目的:volume() 函數的目的是計算並返回CBox物件的體積。
計算方式:體積是通過將CBox對象的長度(length)、寬度(width)和高度(height)相乘來計算得出的。
返回類型:volume() 函數返回一個整數(int),表示計算出的體積值。
使用 CBox 類和 volume() 函數的示例
#include <iostream>
using namespace std;
int main() {
    // 創建一個CBox物件,並初始化其尺寸為10x20x30
    CBox box1(10, 20, 30);
    
    // 調用volume()函數計算並列印箱子的體積
    cout << "The volume of box1 is: " << box1.volume() << endl;
    return 0;
}
在這個示例中,我們創建了一個名為box1的CBox物件,並通過構造函數設置其尺寸為10(長度)、20(寬度)、30(高度)。接著,我們調用了box1物件的volume()成員函數來計算其體積,並通過cout輸出結果到控制台。這個程式的輸出將會是The volume of box1 is: 6000,因為10乘以20乘以30等於6000。