int even( int n ); int OddSum( int List[], int N );
int main() { int List[MAXN], N, i;
scanf("%d", &N); printf("Sum of ( "); for ( i=0; i<N; i++ ) { scanf("%d", &List[i]); if ( even(List[i])==0 ) printf("%d ", List[i]); } printf(") = %d\n", OddSum(List, N));
return 0; }
/* 你的代码将被嵌在这里 */
关键代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int even( int n ){ if(n%2==0){ return 1; } return 0; } int OddSum( int List[], int N ){ int sum=0; for(int i =0;i<N;i++){ if(!even(List[i])){ sum+=List[i]; } } return sum; }
int prime( int p ){ if(p<=1){ return 0; } for(int i =2;i<p;i++){ if(p%i==0){ return 0; } } return 1; } int PrimeSum( int m, int n ){ int sum = 0; for(int i = m;i<=n;i++){ if(prime(i)){ sum+=i; } } return sum; }
习题5-5 使用函数统计指定数字的个数
题目
本题要求实现一个统计整数中指定数字的个数的简单函数。
程序样例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <stdio.h>
int CountDigit( int number, int digit );
int main() { int number, digit;
scanf("%d %d", &number, &digit); printf("Number of digit %d in %d: %d\n", digit, number, CountDigit(number, digit));
return 0; }
/* 你的代码将被嵌在这里 */
关键代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int CountDigit( int number, int digit ){ if(number==0&&digit==0){ return 1; } int count = 0; if(number<0){ number = -1*number; } while(number>0){ if(number%10 == digit){ count ++; } number /= 10; } return count; }
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);
int narcissistic( int number ){ int res = number, i; if(number>=100&&number<=999){ while(number>0){ i = number%10; res -= i*i*i; number /= 10; } }else if(number>=1000&&number<=9999){ while(number>0){ i = number%10; res -= i*i*i*i; number /= 10; } } return !res; } void PrintN( int m, int n ){ for(int i=m+1;i<n;i++){ if(narcissistic(i)){ printf("%d\n",i); } } }