習題5-6 使用函數輸出水仙花數(20 分)


水仙花數是指一個N位正整數(N3),它的每個位上的數字的N次冪之和等於它本身。例如:153=13​​+53​​+33​​。 本題要求編寫兩個函數,一個判斷給定整數是否水仙花數,另一個按從小到大的順序打印出給定區間(m,n)內所有的水仙花數。

函數接口定義:

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

函數narcissistic判斷number是否為水仙花數,是則返回1,否則返回0。

函數PrintN則打印開區間(m, n)內所有的水仙花數,每個數字占一行。題目保證100mn≤10000。

裁判測試程序樣例:

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

/* 你的代碼將被嵌在這里 */

輸入樣例:

153 400

輸出樣例:

153 is a narcissistic number
370
371
#include <stdio.h>
 
int narcissistic( int number )
{
    int a,b,c;
    a=number%10;
    b=number%100/10;
    c=number/100;
    if(number==a*a*a+b*b*b+c*c*c)
    {
        return 1;
    }
    else
    return 0;
}
void PrintN( int m, int n )
{
    for(int i=m+1;i<n;i++)
    {
        if(narcissistic(i)==1)
        {
            printf("%d\n",i);
        }
    }
}

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM