原代碼錯誤
- 冪運算符錯誤:C++ 中
^ 是按位異或,非冪運算。a^3 不等于 a*a*a。
- switch case 常量限制:
case 后必須是編譯期常量表達式,不能是變量或運行時計算結果。
修正方案
1. 立方計算
// 方案 A:自定義函數
int cube(int x) { return x * x * x; }
// 方案 B:標準庫 pow(需 #include <cmath>,返回 double)
int cube(int x) { return (int)std::pow(x, 3); }
2. 替換 switch 為 if-else
if (number == 1) { ... }
else if (number == 2) { ... }
else { ... }
完整邏輯示例
#include <iostream>
#include <cmath>
using namespace std;
int cube(int x) { return x*x*x; }
int main() {
int number;
cin >> number;
if (number == 1) {
cout << cube(2);
} else if (number == 2) {
cout << cube(3);
} else {
cout << "Invalid";
}
return 0;
}
核心提示
- C++ 無內置冪運算符,整數冪用乘法或
std::pow。
switch 僅適用于整型/枚舉常量分支,動態條件請用 if-else。