ps:答案是我的在學習過程當中書寫,可能存在錯漏之處,僅做參考。
做者:cosefy
Date: 2020/1/16ios
第六章:語句數組
練習6.2:函數
練習6.4:
實現:編寫函數,使得用戶輸入一個整數,main函數調用函數獲得階乘。學習
#include<iostream> using namespace std; int fact(int n) { int result = 1; while (n > 1) result *= n--; return result; } int main() { int a; cout << "請輸入一個整數,求階乘: " << endl; cin >> a; cout << "結果:"<<fact(a) << endl; return 0; }
練習6.5:spa
#include<iostream> using namespace std; int fuc(int num) { return num > 0 ? num : -num; } int main() { cout << "請輸入一個整數: " << endl; int a; cin >> a; cout << "絕對值: " << fuc(a) << endl; return 0; }
練習6.6:code
練習6.7:遞歸
#include<iostream> using namespace std; int test1() { static int a = 0; return a++; } int main() { for (int i = 1; i < 5; i++) cout << test1() << endl; return 0; }
練習6.10:生命週期
#include<iostream> using namespace std; void traverse(int* p, int* q) { int tmp; tmp = *p; *p = *q; *q = tmp; } int main() { int a = 20, b = 10; cout << "Before: (a,b)=" << a <<" "<< b << endl; traverse(&a, &b); cout << "After: (a,b)=" << a <<" "<< b << endl; return 0; }
練習6.13:ci
前者是值傳遞,後者是地址傳遞,前者沒法改變實參,後者能夠改變實參。字符串
練習6.15:
練習6.17:
#include<iostream> using namespace std; bool find_upperalpha(const string& s) { for (auto c : s) if (isupper(c)) return true; return false; } void trf_tolower(string& s) { for (auto &c : s) if (isupper(c)) c = tolower(c); } int main() { cout << "請輸出一個字符串: " << endl; string s; cin >> s; cout << "是否有大寫字母:" << find_upperalpha(s) << endl; trf_tolower(s); cout << "把大寫字母轉化爲小寫: " << s << endl; return 0; }
練習6.18:
bool compare(matrix &m1,matrix &m2);
vector<int>:: iterator change_val(int ,vector<int>::iterator);
練習6.22:
#include<iostream> using namespace std; void fuc(int* &p1, int* &p2) { int* q = NULL; q = p1; p1 = p2; p2 = q; } int main() { int a1 = 100, a2 = 200; int* p1 = &a1; int* p2 = &a2; cout << "Before: " << *p1 << " " << *p2 << endl; fuc(p1, p2); cout<< "After: " << *p1 << " " << *p2 << endl; return 0; }
練習6.24:
不能夠用值來傳遞數組。
void print(const int (&a)[10]){/**/}
練習6.25:
#include<iostream> #include<string> using namespace std; int main(int argc, char** argv) { string str; for (int i = 1; i != argc; i++) { str += argv[i]; str += ' '; } cout << str << endl; return 0; }
練習6.27:
#include<iostream> using namespace std; int get_sum(initializer_list<int> i1) { int sum = 0; for (auto elem : i1) sum += elem; return sum; } int main() { initializer_list<int> i2{ 1,2,3,4,5,6 }; cout << get_sum(i2) << endl; return 0; }
練習6.32:
合法,把0-9拷貝到大小爲10的數組中。
練習6.34:
若是輸入爲負數,則將一直遞歸下去。
練習6.35:
val--傳入的值是自減以前的值。
練習6.39:
錯誤,錯誤,正確。