習題5-2 使用函數求奇數和 (15分)


本題要求實現一個函數,計算N個整數中所有奇數的和,同時實現一個判斷奇偶性的函數。

函數接口定義:

int even( int n ); int OddSum( int List[], int N ); 
 

其中函數even將根據用戶傳入的參數n的奇偶性返回相應值:當n為偶數時返回1,否則返回0。函數OddSum負責計算並返回傳入的N個整數List[]中所有奇數的和。

裁判測試程序樣例:

#include <stdio.h> #define MAXN 10 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;
int even( int n ){
    if(n%2==0)
        return 1;
    else 
        return 0;    
    
}

int OddSum( int List[], int N ){
    int sum,i;
    sum=0;
    for(i=0;i<N;i++){
        if(List[i]%2!=0)
            sum+=List[i];
    }
    return sum;
    
}

 

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

輸入樣例:

6
2 -3 7 88 0 15
 

輸出樣例:

Sum of ( -3 7 15 ) = 19




免責聲明!

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



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