本專案實作一款功能完整的複數計算機,支援多複數四則運算、模長比較,並內建十進位實數任意進制轉換功能。專案展示 C++ 核心特性:運算子多載、輸入輸出流多載、命名空間封裝、選單驅動架構 等工程化實踐。
0 (0+0i) 為終止條件。|z| = sqrt(Re²+Im²))。CComnamespace NameCCom {
class CCom {
public:
double Real, Image; // 實部、虛部
CCom(double real = 0, double image = 0) : Real(real), Image(image) {}
// ...
};
}
| 運算子 | 功能 | 回傳型別 |
|---|---|---|
operator>> | 輸入流解析 a+bi 格式 | istream& |
operator<< | 輸出流格式化 (智慧隱藏 0 虛部) | ostream& |
operator+, operator-, operator*, operator/ | 四則運算 (回傳新物件) | CCom |
operator+=, operator-=, operator*=, operator/= | 複合指派 (修改自身) | CCom& |
operator>, operator< | 模長比較 | int (0/1) |
operator==, operator!= | 實部/虛部逐值比較 (含 EPS 容差) | int |
operator>>)採字元流掃描,支援 3+4i, -2.5-3.1i, 5 (純實數), 2i (純虛數) 等格式:
i。error 並重置物件。i 視為純實數。operator<<)EPS (1e-5) → 僅輸出實部。Real+Imagei。Real-Imagei (自動處理負號)。CCom CCom::operator+(const CCom& c) { return CCom(Real + c.Real, Image + c.Image); }
CCom CCom::operator-(const CCom& c) { return CCom(Real - c.Real, Image - c.Image); }
CCom CCom::operator*(const CCom& c) {
return CCom(Real*c.Real - Image*c.Image, Real*c.Image + Image*c.Real);
}
CCom CCom::operator/(const CCom& c) {
double denom = c.Real*c.Real + c.Image*c.Image;
return CCom((Real*c.Real + Image*c.Image)/denom,
(Image*c.Real - Real*c.Image)/denom);
}
double CCom::mod() const { return std::sqrt(Real*Real + Image*Image); }
函數 Jinzhi() 實作十進位整數轉任意基數 (2~36):
n % base 取餘數存入陣列,n /= base,直到商為 0。'A'+rem-10)。void output() { // 印出選單
std::cout << "\t*---------- Hpioneer Calculator Menu ---------*\n"
<< "\t| 1: Multi Complex Add (end with 0) |\n"
<< "\t| 2: Multi Complex Sub (end with 0) |\n"
<< "\t| 3: Multi Complex Mul (end with 0) |\n"
<< "\t| 4: Multi Complex Div (end with 0) |\n"
<< "\t| 5: Complex Compare |\n"
<< "\t| 6: Base Conversion |\n"
<< "\t| 0: Exit |\n"
<< "\t*---------------------------------------------*\n";
}
int main() {
using namespace NameCCom;
int choice;
do {
output();
std::cin >> choice;
switch (choice) {
case 1: Add(); break;
case 2: Sub(); break;
case 3: Mul(); break;
case 4: Div(); break;
case 5: Compare(); break;
case 6: Jinzhi(); break;
case 0: std::cout << "Thank you for using!\n"; break;
default: std::cout << "Invalid option.\n";
}
} while (choice != 0);
return 0;
}
NameCCom 避免全域污染。#define EPS 1e-5 統一浮點比較容差。struct User { char szName[20]; } 預留登入擴充。system("cls") (Windows) 保持介面整潔。0+0i 判斷結束,符合直覺。system("cls") 替換為 ANSI 轉義碼或 ncurses。CCom 邏輯不變。此專案以約 300 行程式碼完整呈現 C++ 物件導向設計、運算子多載藝術與工程化選單架構,是掌握 C++ 進階語法與專案組織的優秀練習範例。