求出0~999之间的所有“水仙花数”并输出。 “水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身,如;153=1+5+3?,则153是一个“水仙花数”。

程序

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
	int i = 0;
	for(; i <= 999; i++)
	{
		int tmp = 0;
		int sum = 0;
		int count = 1;
		tmp = i//把i赋值给tmp
		while(tmp/10)//用while循环判断有几位数
		{
			count ++;//满足条件,计数器++
			tmp /= 10;
		}
		tmp = i;//重新赋值
		while(tmp)//判断i是否为水仙花数
		{
			sum += pow((tmp % 10), count);//pow函数,求一个数的次方,如输入参数pow(3,3),即得27
			tmp /= 10;
		}
		if(sum == i)//如果sum等于i,找到了,并且输出
			printf("%d ", i);
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43857558/article/details/84956989