題目邏輯還原
- 輸入兩個年齡
a, b(以逗號分隔)。
- 定義函數
GetFate(age):計算年齡各位數字之和,若結果 ≥ 10 則遞歸計算,直到得到個位數(即**數字根**)。
- 分別對
a, b 調用 GetFate 得到 fa, fb。
- 定義函數
Add(x, y) 返回 x+y。
- 計算
sum = Add(fa, fb)。
- 再次調用
GetFate(sum) 得到最終緣分值。
- 輸出結果。
完整可運行代碼
#include <stdio.h>
// 計算數字根(遞歸版)
int GetFate(int age) {
int sum = 0;
while (age > 0) {
sum += age % 10;
age /= 10;
}
if (sum >= 10) return GetFate(sum); // 遞歸直到個位數
return sum;
}
// 簡單加法
int Add(int a, int b) { return a + b; }
int main() {
int a, b;
printf("請輸入兩個年齡(逗號分隔):");
scanf("%d,%d", &a, &b);
a = GetFate(a);
b = GetFate(b);
int sum = Add(a, b);
int fate = GetFate(sum);
printf("您和她的緣分是:%d\n", fate);
return 0;
}
關鍵知識點
- 數字根公式:
dr(n) = 1 + (n-1) % 9(n>0),可替代遞歸實現 O(1) 計算。
- 遞歸終止條件:
sum < 10 時返回,防止無限遞歸棧溢出。
- scanf 格式:
"%d,%d" 匹配逗號分隔,輸入時必須帶逗號(如 25,30)。
測試用例
| 輸入 | 過程 | 輸出 |
| 25,30 | 2+5=7, 3+0=3 → 7+3=10 → 1+0=1 | 緣分是:1 |
| 19,28 | 1+9=10→1, 2+8=10→1 → 1+1=2 | 緣分是:2 |
| 99,99 | 9+9=18→9, 9+9=18→9 → 9+9=18→9 | 緣分是:9 |
