2018.10.1 練習
阿新 • • 發佈:2018-12-13
1. 遞迴求階乘(5!)
static int f(int n)
{
if (n == 1) // 遞迴終止條件
return 1;
return n*f(n - 1);
}
int main()
{
printf("5! = %d", f(5));
system("pause");
return 0;
}
結果如圖:
2. 判斷迴文數
int fun(long n) { int len = 0; int ret = 1; int i = 0, j = 0, k = 0; int left, right; while (n == 0) //求n的位數 { n %= 10; n /= 10; len++; } for (i = 1; i < len / 2; i++) { for (j = 0; j < len - i; j++) { left = n / 10; } for (k = 0; k < i; k++) { right = n % 10; } if ((left == i) && (right == 1)) { continue; } else { ret = 0; break; } } return ret; } int main() { long num; printf("輸入一個小於6位的數字:\n"); scanf("%ld", &num); int result = fun(num); if (1 == result) { printf("這個數是迴文數!\n"); } else if (0 == result) { printf("這個數不是迴文數!\n"); } system("pause"); return 0; }
結果如圖: