赞
踩
题目:
求出0~100000之间的所有“水仙花数”并输出。
“水仙花数”是指一个n位数,其各位数字的n次方之和确好等于该数本身,如:153=1^3+5^3+3^3,则153是一个“水仙花数”。
看到题目我们先要确定要做的几个事情
1.先算出给定的数的位数n
2.算出这个数的各个位上的数的n次方
3.然后将这些数加起来和给定的数相比,如果相同则为水仙花数
- int tem(int i)
- {
- int count = 1;
- while (i / 10)
- {
- count++;
- i = i / 10;
- }
- return count;
- }
这里会用到一个函数pow(x,y),其作用是计算x的y次方(需要加上头文件math.h)
- int temp = i;//保证给定的i的值不会改变
-
- if (i != 0)
- {
- while (temp)
- {
- sum += pow((temp % 10), n);
- temp = temp / 10;
- }
- }
- else
- {
- sum = 1;
- }
- if (sum == i)
- {
- printf("%d\n", i);
- }
- #define _CRT_SECURE_NO_WARNINGS 1
- #include<stdio.h>
- #include<string.h>
- #include<math.h>
- #include<time.h>
- #include<stdlib.h>
- int tem(int i)
- {
- int count = 1;//水仙花数从一位数开始
- while (i / 10)
- {
- count++;
- i = i / 10;
- }
- return count;
- }
- int main()
- {
- int i;
- for (i = 0; i <= 100000; i++)
- {
- int sum = 0;
- int n = tem(i);//求出位数
- int temp = i;//保证给定的i的值不会改变
-
- if (i != 0)
- {
- while (temp)
- {
- sum += pow((temp % 10), n);
- temp = temp / 10;
- }
- }
- else
- {
- sum = 1;
- }
-
- if (sum == i)
- {
- printf("%d\n", i);
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。