Exercise 5-6 Use a function to output the number of daffodils (20 point(s))

The number of daffodils refers to an N-digit positive integer (N≥3), and the sum of the N-th power of the number on each digit is equal to itself. For example: 153=1 ​3+5 3+3^3. This question requires writing two functions, one to determine whether a given integer is the number of daffodils, the other to print out all the numbers of daffodils in a given interval (m, n) in ascending order.

Function interface definition:

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

The function narcissistic judges whether number is a daffodil number, and returns 1 if it is, otherwise it returns 0.

The function PrintN prints all the numbers of daffodils in the open interval (m, n), and each number occupies one line. The question is guaranteed to be 100≤m≤n≤10000.

Sample referee test procedure:

#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;
}

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

Input sample:

153 400

Sample output:

153 is a narcissistic number
370
371

answer:

int narcissistic( int number )
{
    
      //判断number是否为水仙花数,是则返回1,否则返回0。
	int t=number;
	int sum=0;
	int p;
	int cnt=0;
	while(t)
	{
    
    
		t/=10;
		cnt++;
	}
	t=number;
	while(t)
	{
    
    
		int i;
		p=t%10;
		int x=1;
		for(i=1;i<=cnt;i++)
		{
    
    
			x*=p;
		}
		sum+=x;
		t/=10;
	}
	if(sum==number) return 1;
	else return 0;
}
void PrintN( int m, int n )
{
    
      //打印开区间(m, n)内所有的水仙花数,每个数字占一行
	int i; //循环变量 
	for(i=m+1;i<n;i++) //循环区间(由于是开区间所以前面要加一,右面没有等于,取不到) 
	{
    
    
		int sum=0; // 每位数分解后乘方的和(和区间的数比较 相等就是水仙花数) 
		int t=i; //中间变量t,保护i的值,后面拿t做运算 
		int cnt=0; //计数器,算水仙花数有几位 
		while(t) //循环算水仙花数的位数 
		{
    
    
			t/=10;
			cnt++;	
		}
		t=i; //由于t在上面算位数时t的值发生改变,所以重新赋值一次 
		int p; //存放每一数 ,用于后面的乘方运算 
		while(t)
		{
    
    
			p=t%10; //取最后一位数 
			int s; //循环变量 
			int x=1; //定义x为每一位数的乘方和 ,初值为1 
			for(s=1;s<=cnt;s++)
			{
    
    
				x*=p; //累乘 
			}
			sum+=x; //累加 
			t/=10; //每次最后t都要/10把最后一位数去掉 
		}
		if(sum==i) printf("%d\n",i); //如果相等就是水仙花数 
	}
}

Guess you like

Origin blog.csdn.net/qq_44715943/article/details/114584157