C 語言實例 – 判斷Armstrong數(shù)(阿姆斯壯數(shù))

C 語言實例 - 判斷Armstrong數(shù)(阿姆斯壯數(shù))

C 語言實例 C 語言實例

Armstrong 數(shù),就是n位數(shù)的各位數(shù)的n次方之和等于該數(shù),如:

153=1^3+5^3+3^3
1634=1^4+6^4+3^4+4^4

實例

#include <stdio.h> int main() { int number, originalNumber, remainder, result = 0; printf("輸入三位數(shù): "); scanf("%d", &number); originalNumber = number; while (originalNumber != 0) { remainder = originalNumber%10; result += remainder*remainder*remainder; originalNumber /= 10; } if(result == number) printf("%d 是 Armstrong 數(shù)",number); else printf("%d 不是 Armstrong 數(shù)",number); return 0; }

運行結果:

輸入三位數(shù): 371
371 是 Armstrong 

實例 - 兩數(shù)之間的 Armstrong 數(shù)

#include <stdio.h> #include <math.h> int main() { int low, high, i, temp1, temp2, remainder, n = 0, result = 0; printf("輸入兩個整數(shù): "); scanf("%d %d", &low, &high); printf("%d 和 %d 之間的 Armstrong 數(shù)為: ", low, high); for(i = low + 1; i < high; ++i) { temp2 = i; temp1 = i; // 計算 while (temp1 != 0) { temp1 /= 10; ++n; } while (temp2 != 0) { remainder = temp2 % 10; result += pow(remainder, n); temp2 /= 10; } if (result == i) { printf("%d ", i); } n = 0; result = 0; } return 0; }

運行結果:

輸入兩個整數(shù): 100 1000
100 和 1000 之間的 Armstrong 數(shù)為: 153 370 371 407

實例 - 使用函數(shù)判斷Armstrong 數(shù)

#include <stdio.h> #include <math.h> int checkPrimeNumber(int n); int checkArmstrongNumber(int n); int main() { int n, flag; printf("輸入正整數(shù): "); scanf("%d", &n); // 檢測素數(shù) flag = checkPrimeNumber(n); if (flag == 1) printf("%d 是素數(shù)。\n", n); else printf("%d 不是素數(shù)\n", n); // 檢測 Armstrong 數(shù) flag = checkArmstrongNumber(n); if (flag == 1) printf("%d 是 Armstrong 數(shù)。", n); else printf("%d 不是 Armstrong 數(shù)。",n); return 0; } int checkPrimeNumber(int n) { int i, flag = 1; for(i=2; i<=n/2; ++i) { // 非素數(shù)條件 if(n%i == 0) { flag = 0; break; } } return flag; } int checkArmstrongNumber(int number) { int originalNumber, remainder, result = 0, n = 0, flag; originalNumber = number; while (originalNumber != 0) { originalNumber /= 10; ++n; } originalNumber = number; while (originalNumber != 0) { remainder = originalNumber%10; result += pow(remainder, n); originalNumber /= 10; } // 判斷條件 if(result == number) flag = 1; else flag = 0; return flag; }

輸出結果為:

輸入正整數(shù): 371
371 不是素數(shù)
371 是 Armstrong 數(shù)。

C 語言實例 C 語言實例

相關文章
亚洲国产精品第一区二区,久久免费视频77,99V久久综合狠狠综合久久,国产免费久久九九免费视频