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

水仙花數(shù)是指一個N位正整數(shù)(N≥3),它的每個位上的數(shù)字的N次冪之和等于它本身。例如:153=1?3??+5?3??+3?3??。 本題要求編寫兩個函數(shù),一個判斷給定整數(shù)是否水仙花數(shù),另一個按從小到大的順序打印出給定區(qū)間(m,n)內(nèi)所有的水仙花數(shù)。

函數(shù)接口定義:

int?narcissistic(?int?number );

void?PrintN(?int?m,?int?n );

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

函數(shù)PrintN則打印開區(qū)間(m,?n)內(nèi)所有的水仙花數(shù),每個數(shù)字占一行。題目保證100≤m≤n≤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




int narcissistic( int number ){

????int i,n=0 , sum=0 , count=0;?

? ? n = number;?

? ? while(n){? ?

? ? ? ? count++;?

? ? ? ? n/=10;?

? ? }?


? ? n = number;?

? ? while(n){

????????i=n%10;

? ? ? ? sum += (int)pow(i, cnt);

? ? ? ? n/=10;

? ? }?


? ? if(sum == number)?

? ? ? ? return 1;?

? ? else?

? ? ? ? return 0;?

}

void PrintN( int m, int n ){?


? ? int i;?


? ? for(i=m+1;i<n;i++)?

? ? ? ? if(narcissistic(i))?

? ? ? ? ? ? printf("%d\n", i);?

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容