天天看点

C语言之水仙花数

水仙花数

题目描述

水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:​​本题要求编写程序,计算所有N位的水仙花数。

输入

输入在一行中给出一个正整数N。

输出

按递增顺序输出所有N位水仙花数,每个数字占一行。

样例输入

3
           

样例输出

153
370
371
407
           

代码块:

#include<stdio.h>
#include<math.h>
int main()
{
	int i,n,b,a,m,s=0;
	scanf("%d",&n);
	m=pow(10,n);
	for(i=pow(10,n-1);i<m;i++){
		a=i;
		while(a!=0){
			b=a%10;
			s+=pow(b,n);
			a=a/10;
		}
		if(s==i){
			printf("%d\n",s);
		}
		s=0;
	}
}
           

注释:

#include<stdio.h>		//C标准输入输出库
#include<math.h>		//数学库
int main()
{
	int i,n,b,a,m,s=0;	//定义参数
	scanf("%d",&n);
	m=pow(10,n);		//数学函数中计算幂的函数
	for(i=pow(10,n-1);i<m;i++){
		a=i;
		while(a!=0){
			b=a%10;		//b为每次所取的个位数数值
			s+=pow(b,n);//s为个位上的n次幂的和
			a=a/10;		//a为每次退位(每次去掉一个个位)后的数
		}
		if(s==i){
			printf("%d\n",s);
		}
		s=0;			//每次运算清空s的值
	}
}
           

继续阅读