- 按示例學習 C 時間
- 按示例學習 C - 主頁
- C 示例 - 簡單程式
- C 示例 - 迴圈/迭代
- C 示例 - 模式
- C 示例 - 陣列
- C 示例 - 字串
- C 示例 - 數學
- C 示例 - 連結串列
- C 程式設計有用資源
- 按示例學習 C - 快速指南
- 按示例學習 C - 資源
- 按示例學習 C - 討論
C 語言阿姆斯壯數程式
阿姆斯壯數等於其各個數字的立方和。例如,153 是阿姆斯壯數,因為 -
153 = (1)3 + (5)3 + (3)3 153 = 1 + 125 + 27 153 = 153
演算法
此程式的演算法非常簡單 -
START Step 1 → Take integer variable Arms Step 2 → Assign value to the variable Step 3 → Split all digits of Arms Step 4 → Find cube-value of each digits Step 5 → Add all cube-values together Step 6 → Save the output to Sum variable Step 7 → If Sum equals to Arms print Armstrong Number Step 8 → If Sum not equals to Arms print Not Armstrong Number STOP
虛擬碼
我們可以草擬以上演算法的虛擬碼,如下所示 -
procedure armstrong : number
check = number
rem = 0
WHILE check IS NOT 0
rem ← check modulo 10
sum ← sum + (rem)3
divide check by 10
END WHILE
IF sum equals to number
PRINT armstrong
ELSE
PRINT not an armstrong
END IF
end procedure
實現
此演算法的實現如下。你可以更改 arms 變數的值,然後執行和檢查你的程式 -
#include <stdio.h>
int main() {
int arms = 153;
int check, rem, sum = 0;
check = arms;
while(check != 0) {
rem = check % 10;
sum = sum + (rem * rem * rem);
check = check / 10;
}
if(sum == arms)
printf("%d is an armstrong number.", arms);
else
printf("%d is not an armstrong number.", arms);
return 0;
}
輸出
程式的輸出應該是 -
153 is an armstrong number.
mathematical_programs_in_c.htm
廣告