Re: [問題] 用C++寫程式

看板C_and_CPP作者 (妄想制御)時間14年前 (2009/12/15 20:08), 編輯推噓5(503)
留言8則, 7人參與, 最新討論串3/3 (看更多)
※ 引述《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
good
12/15 20:57, 1F

12/15 21:03, , 2F
真讚
12/15 21:03, 2F

12/15 21:12, , 3F
STL愈來愈方便了~~~ 讚
12/15 21:12, 3F

12/15 21:15, , 4F
好多沒看過的指令= =~謝謝大大的範例我會參考的
12/15 21:15, 4F

12/15 22:03, , 5F
for下面 auto 那行的用法小弟還真的第一次看過Q_Q~
12/15 22:03, 5F

12/15 22:21, , 6F
是lambda expression
12/15 22:21, 6F

12/16 13:29, , 7F
原po快哭了 XD
12/16 13:29, 7F

12/17 12:58, , 8F
從來沒看過這種寫法 cool
12/17 12:58, 8F
文章代碼(AID): #1B9tmyxN (C_and_CPP)
文章代碼(AID): #1B9tmyxN (C_and_CPP)