C语言经典题:求水仙花数(详解)

 想当初,怎么写都写不出这道破题,现在写起来感觉好简单

#include<stdio.h>
#include<math.h>
int main()
{
	
	for (int i = 0;i < 999999;i++)
	{
		int count = 0;
		int tmp = i;//因为i后面要用到,所以找个替罪羊,不让i为零
		//先求一个数有多少位
		while (tmp != 0)
		{
			count++;
			tmp = tmp / 10;
		}
		//接着求一个数的次方
		//注意:这里tmp变为零了,所以重新让tmp变为i
		tmp = i;
		int sum = 0;
		while (tmp != 0)
		{//创建一个累加变量sum来存储和
			sum+=pow(tmp % 10, count);//pow 需要包含头文件<math.h>
			tmp /= 10;
		}
		//判断是否为水仙花数,如果是就打印
		if (sum == i)
		{
			printf("%d\n", sum);
		}
	}
	return 0;
}

晚安,各位宝

猜你喜欢

转载自blog.csdn.net/zsd2829568515/article/details/134498042