一、輸入兩個數
二、用到兩個函數:
//判斷number是不是水仙花數,是返回1,否返回0
int narcissistic (int number);
//打印區間m,n之間的全部水仙花數
void PrintN(int m, int n);函數
//函數聲明 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; } //判斷number是不是水仙花數,是返回1,否返回0 int narcissistic (int number){ int t = number; //計數 int count = 1; //統計number是幾位數 while(t>9){ count++; t/=10; } //設置一個返回值,是水仙花則反judge=1;不然judge=0; int judge = 0; int b = number; int sum = 0; while(b>0){ int a = b%10; b/=10; int p = a; //這一行不會不懂吧->_-> 各個位的位數次方 int j = 1; while(j<count){ p *= a; j++; } sum += p; } if(sum == number){ judge = 1; } return judge; } //打印區間m,n之間全部的水仙花數 void PrintN(int m, int n){ int i; for(i = m+1; i<n; i++){ //函數嵌套調用函數 if(narcissistic(i)){ printf("%d\n",i); } } }
(1)忘記聲明函數接口了,低級錯誤,千萬不要忘。否則之後侍奉女朋友時作事忘東忘西可就有你好受了。。。
(2)在統計number是幾位數時,判斷條件不對。解決:由於我定義的count計數是從1開始,因此只要知足t>9或者t>=10時便可知足判斷位數的條件。詳細見代碼。spa