Menu Close

C语言检查输入数据是不是阿姆斯壮数

阿姆斯壮数(armstrongnumber) 定义:阿姆斯壮数(armstrongnumber) 是等于其数字的立方数之和的数字,例如:0,1,153,370,371,407等。
现在试着理解为什么153是一个阿姆斯壮数字, 153 = (1*1*1)+(5*5*5)+(3*3*3)。

153 = (1*1*1)+(5*5*5)+(3*3*3)
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153

C语言检查输入数据是不是阿姆斯壮数

#include<stdio.h>
int main()
{
   int num,copy_of_num,sum=0,rem;

   //Store input number in variable num
   printf("\nEnter a number:");
   scanf("%d",&num);

   /* Value of variable num would change in the
      below while loop so we are storing it in
      another variable to compare the results
      at the end of program
   */
   copy_of_num = num;

   /* We are adding cubes of every digit
    * and storing the sum in variable sum
    */
   while (num != 0)
   {
      rem = num % 10;
      sum = sum + (rem*rem*rem);
      num = num / 10;
   }

   /* If sum of cubes of every digit is equal to number
    * itself then the number is Armstrong
    */
   if(copy_of_num == sum)
      printf("\n%d is an Armstrong Number",copy_of_num);
   else
      printf("\n%d is not an Armstrong Number",copy_of_num);
   return(0);
}

 

Enter a number:371

371 is an Armstrong Number
Process returned 0 (0x0) execution time : 4.139 s
Press any key to continue.
READ  C语言练习:发现两个数的最大公约数(GCD)
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C 决策和循环语句

Related Posts