Re: [問題] 請問初學C語言推薦書(文長

看板C_and_CPP作者 (卍~邁斯納效應~卍)時間6年前 (2018/05/10 22:38), 6年前編輯推噓1(100)
留言1則, 1人參與, 6年前最新討論串3/7 (看更多)
※ 引述《freexq (快樂蕃茄)》之銘言: : 題目:5個數字取最大值 : 貢獻三種寫法,希望有人能貢獻更多寫法 原文在問C........結果你給都C++........................... 那我也來一個 #include <iostream> #include <numeric> #include <thread> #include <vector> using namespace std; int main() { const vector<int> numbers { 9, 15, 87, 4, 1, 2 }; volatile int maxNumber = numeric_limits<int>::min(); vector<thread> threads; for (const int n : numbers) threads.emplace_back(thread([&maxNumber](const int number) { this_thread::sleep_for(chrono::milliseconds(number)); maxNumber = number; }, n)); for (auto& t : threads) t.join(); cout << "maxNumber: " << maxNumber << endl; return 0; } : 根據以往寫程式的經驗,一個題目不會只有一種解法 : 資料結構也許不同以外,程式流程(演算法)也不同 : 以下我的 : 第一種解法是手刻 : 第二種解法是利用sort()函式排列由小至大,然後取最大數 : 第三種解法是偷吃步,直接呼叫max_element()函式 : 基本上作業或考試應該用第一種手刻 : 而第二、三種寫法應該是自己開發程式情況下,直接取適合函式出來用 : 優點是比較不容易出錯,而且更節省時間 : 自己手刻則不一定一次到位,可能要test或debug。 : 以下是程式碼 : (一) : #include <iostream> : using namespace std; : int main() : { : int num[5],max; : //輸入五個整數至陣列num[] : cout<<"請輸入5個數字"<<endl; : for(int i=0;i<5;i++) : cin>>num[i]; : //逐一和整個陣列比較,取最大 : max=num[0]; : for(int i=1;i<5;i++) : { : if(num[i]>max) : max=num[i]; : } : //輸出最大數 : cout<<"\n最大數為 "<<max<<endl; : return 0; : } : (二) : #include <iostream> : #include <algorithm> : using namespace std; : int main () : { : int num[5]; : //輸入5個int數字至num[] : cout<<"請輸入5個數字"<<endl; : for(int i=0;i<5;i++) : cin>>num[i]; : //開始排序,由小到大 : sort(num,num+5); : //輸出最大數 : cout<<"\n最大數為 "<<num[4]<<endl; : return 0; : } : (三) : #include <iostream> : #include <algorithm> //使用max_element()函數 : using namespace std; : int main() : { : int num[5]; : //輸入5個int數字至num[] : cout<<"請輸入5個數字"<<endl; : for(int i=0;i<5;i++) : cin>>num[i]; : //輸出最大數 : //注意max_element()函數傳回 指標 : cout<<"\n最大數為 "<<*max_element(num,num+5)<<endl; : return 0; : } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.217.135.218 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1525963083.A.49B.html ※ 編輯: dritchie (180.217.135.218), 05/10/2018 22:39:18

05/10 22:56, 6年前 , 1F
負數不會爆炸嗎
05/10 22:56, 1F
文章代碼(AID): #1Qz5bBIR (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1Qz5bBIR (C_and_CPP)