实验5-9 使用函数输出水仙花数(20 分)

实验5-9 使用函数输出水仙花数(20 分)

水仙花数是指一个$N$位正整数$(N≥3)$,它的每个位上的数字的N次幂之和等于它本身。例如:$153=13+53+33$。 本题要求编写两个函数,一个判断给定整数是否水仙花数,另一个按从小到大的顺序打印出给定区间(m,n)内所有的水仙花数。

函数接口定义:

1
2
int narcissistic( int number );
void PrintN( int m, int n );

函数narcissistic判断number是否为水仙花数,是则返回1,否则返回0。

函数PrintN则打印开区间(m, n)内所有的水仙花数,每个数字占一行。题目保证100≤mn≤10000。

裁判测试程序样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>

int narcissistic( int number );
void PrintN( int m, int n );

int main()
{
int m, n;

scanf("%d %d", &m, &n);
if ( narcissistic(m) ) printf("%d is a narcissistic number\n", m);
PrintN(m, n);
if ( narcissistic(n) ) printf("%d is a narcissistic number\n", n);

return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

1
153 400

输出样例:

1
2
3
153 is a narcissistic number
370
371
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include<math.h>
int narcissistic( int number );
void PrintN( int m, int n );

int main()
{
int m, n;

scanf("%d %d", &m, &n);
if ( narcissistic(m) ) printf("%d is a narcissistic number\n", m);
PrintN(m, n);
if ( narcissistic(n) ) printf("%d is a narcissistic number\n", n);

return 0;
}
int narcissistic( int number ) {
int i=0,k,sum=0,s;
int a[999];
s=number;
do {
i++;
a[i]=number%10;
number=number/10;
}
while(number!=0);
k=i;
do {
sum=sum+pow(a[i],k);
i--;
}
while(i>0);
if(sum==s)
return 1;
else
return 0;
}
void PrintN( int m, int n ) {
int i,k,z;
for(i=m+1;i<n;i++)
if(narcissistic(i)==1)
printf("%d\n",i);
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×