ps:答案是我的在學習過程當中書寫,可能存在錯漏之處,僅做參考。
做者:cosefy
Date: 2020/1/15ios
第三章:語句學習
練習5.3:spa
代碼可讀性下降了。3d
while(val<=10) sum+=val,++val;
練習5.4:code
練習5.5:blog
#include<iostream> #include<vector> using namespace std; int main() { //vector<string> str{ "甲","乙","丙" }; int score; string rank; while (cin >> score) { if (score < 60) rank = "丙"; else if (score < 90) rank = "乙"; else rank = "甲"; cout << rank << endl; return 0; } }
練習5.6:ip
rank = score > 90 ? "甲" : score > 60 ? "乙":"丙";
練習5.7:ci
練習5.9:string
#include<iostream> #include<vector> using namespace std; int main() { int a_count = 0, e_count = 0, i_count = 0, o_count = 0, u_count = 0; int other_count = 0; char c; while (cin >> c) if (c == 'a') ++a_count; else if (c == 'e') ++e_count; else if (c == 'i') ++i_count; else if (c == 'o') ++o_count; else if (c == 'u') ++u_count; else ++other_count; cout << "a: " << a_count << endl; cout << "e: " << e_count << endl; cout << "i: " << i_count << endl; cout << "o: " << o_count << endl; cout << "u: " << u_count << endl; return 0; }
練習5.10:it
代碼形式以下所示:
case 'a': case'A': ++a_count; break;
練習5.11:
修改while判斷語句爲:
while (cin >>noskipws>> c)
這樣不會忽略空白,另外加上統計製表符等的case語句就能夠了。
練習5.12:
保留上一個字符,若是當前字符爲'f'或'i'或'l',則判斷上個字符是不是'f'。
練習5.13:
練習5.14:
#include<iostream> #include<vector> using namespace std; int main() { string now_word, last_word,record_word; int max = 1,count=1,flag=0; while (cin >> now_word) { if (now_word == last_word) { ++count; last_word = now_word; } else { if (max < count) { max = count; record_word = last_word; } count = 1; last_word = now_word; flag = 1; //標記出現了不重複的單詞 } } if (flag==0) cout << "僅有單詞"<<now_word << "出現了" << count << "次" << endl; else cout << record_word << "出現了"<<max << "次" << endl; return 0; }
練習5.15:
練習5.17:
#include<iostream> #include<vector> using namespace std; int main() { vector<int>v1{ 1,0,2,2,3,5 }; vector<int>v2{ 1,0,2,2, }; auto it1 = v1.begin(); auto it2 = v2.begin(); for (; it2 != v2.end(); ++it1, it2++) if (*it2 != *it1) break; cout << (it2 == v2.end() ? "YES" : "NO"); return 0; }
練習5.18:
練習5.20:
#include<iostream> #include<vector> using namespace std; int main() { string last_word, accur_word; bool flag = false; while (cin >> accur_word) { if (accur_word == last_word) { cout << accur_word << endl; break; } else { last_word = accur_word; flag = true; } } if (!flag) cout << "不連續重複" << endl; return 0; }
練習5.23:
#include<iostream> using namespace std; int main() { int m, n; cin >> m >> n; cout << "m/n:"<<m / n << endl; return 0; }
練習5.24:
練習5.25:
#include<iostream> using namespace std; int main() { int m, n; while (cin >> m >> n) { try { if (n == 0) throw runtime_error("除數不可爲0"); cout << "m/n:" << m / n << endl; } catch (runtime_error err) { cout << err.what() << "\nTry Again? Enter Y or N" << endl; char c; cin >> c; if (!cin||c == 'N') break; } } return 0; }