Re: [問題] 用C++寫程式
※ 引述《asdf12345 (= =!!)》之銘言:
: : 5.利用某一迴圈敘述輸入20個整數,計算輸入的整數有多少個奇
: : 數,有多少個偶數,這些奇數或偶數的總合與平均值又各為多少
: : ?
第五題:
我只做了偶數部份 奇數就請你自己想辦法吧
#include<iostream>
#include<algorithm>
#include<numeric>
using namespace std;
int main() {
int a[20];
for(auto i=0; i<20; i++) cin >> a[i];
auto f = [](int x){return !(x&1);};
cout << count_if(a, a+20, f) << "個偶數" << endl;
cout << "總和: "
<< accumulate(a, a+20, 0, [f](int x, int y){return f(y)?x+y:x;})
<< endl;
cout << "平均: "
<< accumulate(a, a+20, 0, [f](int x, int y){return f(y)?x+y:x;}) /
(double)count_if(a, a+20, f)
<< endl;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.30.32
推
12/15 20:57, , 1F
12/15 20:57, 1F
推
12/15 21:03, , 2F
12/15 21:03, 2F
→
12/15 21:12, , 3F
12/15 21:12, 3F
→
12/15 21:15, , 4F
12/15 21:15, 4F
推
12/15 22:03, , 5F
12/15 22:03, 5F
→
12/15 22:21, , 6F
12/15 22:21, 6F
推
12/16 13:29, , 7F
12/16 13:29, 7F
推
12/17 12:58, , 8F
12/17 12:58, 8F
討論串 (同標題文章)