問題: How to implement 階層運算
n! = 1*2*3*4*…n!
方法1:
- 兩層迴圈處理
方法2:
- 一層迴圈處理
int main() {
int num = 0;
int each_sum = 1;
int total_sum = 1;
cout << "輸入一個數字: " << endl;
cin >> num;
int i = 1;
for (i; i <= num; i++) {
each_sum = 1*i;
total_sum *= each_sum;
}
cout << "計算" << num << "!: " << total_sum << endl;
return 0;
}
- 計算 1! + 2! + 3! + ….+ n!
int main() {
int num = 0;
int each_sum = 1;
int total_sum = 0;
cout << "輸入一個數字: " << endl;
cin >> num;
int i = 1;
for (i; i <= num; i++) {
each_sum *= i;
total_sum += each_sum;
}
cout << "1!+2!+3!+...+n! = " << total_sum << endl;
return 0;
}