问题描述
打印出所有的水仙花数。水仙花数是指一个三位数,其各位数字的立方和等于数本身。例如153 = 1+5+3,因此153为水仙花数。
分析
两种思路:
(1)每位数字0-9(百位数为1-9),程序结构可设计成三层循环,当数字组合符合要求时就输出。
(2)直接对100-999之间的数字分离出三个数位上的数字进行验证,符合要求时输出
源程序
C语言
使用思路(1)
#include<stdio.h>
#include<math.h>
int main()
{
int b,s,g,num=0;
for(b=1;b<10;b++)
for(s=0;s<10;s++)
for(g=0;g<10;g++)
{
if(pow(b,3)+pow(s,3)+pow(g,3) == b*100+s*10+g)
{
printf("%d\n",b*100+s*10+g);
num+=1;
}
}
printf("共有%d个水仙花数",num);
return 0;
}
//153
//370
//371
//共有3个水仙花数
Python
使用思路(2)编写
#coding:gbk
i = 0
for num in range(100,1000):
#分离三个数位上的数字
b = num//100
s = (num-b*100)//10
g = num-b*100-s*10
if num == b**3 + s**3 + g**3:
print(num)
i += 1
print(i)
'''
153
370
371
407
4
'''
可见两次运行的结果是不一样的,C语言里为何没有输出407这个水仙花数呢?
问题出在pow()
函数上。(C语言第十行代码上)
pow()返回的数字为double型浮点数,浮点数和整型比较时可能会因为精度不同而出现不相等的情况出现。(数字比较时一定要注意数据类型)
将第十行代码修改为:
if((int)(pow(b,3)+pow(s,3)+pow(g,3)) == b*100+s*10+g)
即可解决问题。
**