求出0〜999之间的所有“水仙花数”并输出。



水仙花数是指一个 n 位数 ,它的每个位上的数字的 n 次幂之和等于它本身。在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number)。
例如153、370、371及407就是三位数的水仙花数,其各个数之立方和等于该数:
153 = 1^3 + 5^3 + 3^3。
370 = 3^3 + 7^3 + 0^3。
371 = 3^3 + 7^3 + 1^3。
407 = 4^3 + 0^3 + 7^3。

#include<stdio.h>
#include<windows.h>
#include<math.h>
int isWaterFlower(int x)
{
	int n = 0;
	int sum = 0;
	int y = x;
	if (x >=0&&x <=10)//判断是几位数。
	{
		n=1;
	}
	else if (x >= 10&&x <=100)
	{
		n = 2;
	}
	else if (x >= 100&&x < 10000)
	{
		n = 3;
	}
	else
	{
		printf("error");
		return 0;
	}
	while (x)
	{
		sum += pow(x % 10, n);
		x = x / 10;
	}
	if (y == sum)//一位数字的n次幂的和正好等于这个数本身。
	{
		return 1;
	}
	
		return 0; 
}

int main()
{
	int i = 0;
	for (; i < 1000; i++)
	{
		if (isWaterFlower(i))
		{
			printf("%d\n", i);
		}
	}
	printf("\n");
	system("pause");
	return 0;
}
输出结果为:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值