习题5-6 使用函数输出水仙花数
1 #include <stdio.h> 2 int narcissistic(int number); 3 void PrintN(int m, int n); 4 5 int main() 6 { 7 int m, n; 8 9 scanf_s("%d %d", &m, &n); 10 if (narcissistic(m)) printf("%d is a narcissistic number\n", m); 11 PrintN(m, n); 12 if (narcissistic(n)) printf("%d is a narcissistic number\n", n); 13 14 return 0; 15 } 16 17 int narcissistic(int number) 18 { 19 int x; //x分离出的每位数字 20 int count = 0; //count统计数的位数 21 int temp; //等于number的临时变量 22 int sum = 0; //每个数字的幂之和 23 int pow; //幂 24 temp = number; 25 26 do 27 { 28 count++; 29 temp = temp / 10; 30 } while (temp!=0); 31 32 temp = number; 33 for (int i = 0; i < count; i++) 34 { 35 x = temp % 10; 36 37 pow = 1; 38 39 for (int j = 1; j <= count; j++) 40 { 41 pow = pow * x; 42 } 43 44 sum = sum + pow; 45 46 temp = temp / 10; 47 } 48 if (sum == number) 49 { 50 return 1; 51 } 52 else 53 { 54 return 0; 55 } 56 } 57 void PrintN(int m, int n) 58 { 59 for (int i = m + 1; i < n; i++) 60 { 61 if (narcissistic(i)) 62 { 63 printf("%d\n", i); 64 } 65 } 66 }