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

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

实现

此算法的实现如下。你可以更改 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
广告