習(xí)題5-2 使用函數(shù)求奇數(shù)和 (15 分)
1. 題目摘自
https://pintia.cn/problem-sets/12/problems/302
2. 題目?jī)?nèi)容
本題要求實(shí)現(xiàn)一個(gè)函數(shù)坦冠,計(jì)算 N
個(gè)整數(shù)中所有奇數(shù)的和幢码,同時(shí)實(shí)現(xiàn)一個(gè)判斷奇偶性的函數(shù)。
函數(shù)接口定義:
int even( int n )
;
int OddSum( int List[], int N )
;
其中函數(shù) even
將根據(jù)用戶傳入的參數(shù) n
的奇偶性返回相應(yīng)值:當(dāng) n
為偶數(shù)時(shí)返回 1
顾犹,否則返回 0
。函數(shù) OddSum
負(fù)責(zé)計(jì)算并返回傳入的 N
個(gè)整數(shù) List[]
中所有奇數(shù)的和脸候。
輸入樣例:
6
2 -3 7 88 0 15
輸出樣例:
Sum of ( -3 7 15 ) = 19
3. 源碼參考
#include<iostream>
using namespace std;
#define MAXN 10
int even(int n);
int OddSum(int List[], int n);
int main()
{
int List[MAXN], n, i;
cin >> n;
cout << "Sum of ( ";
for (i = 0; i < n; i++)
{
cin >> List[i];
if (even(List[i]) == 0)
{
cout << List[i] << " ";
}
}
cout << ") = " << OddSum(List, n) << endl;
return 0;
}
int even(int n)
{
if (n % 2 != 0)
{
return 0;
}
return 1;
}
int OddSum(int List[], int n)
{
int s = 0;
for (int i = 0; i < n; i++)
{
if (even(List[i]) == 0)
{
s += List[i];
}
}
return s;
}