1.驗證性實驗部分
①函數聲明和函數定義各自的作用及二者的區別:
函數聲明就是調用函數之前提示一下有這個函數
函數定義就是寫一個函數
②什么是形參?什么是實參?函數參數和返回值在函數中起到什么作用?
函數定義時寫的參數叫做形參,這些參數只是給計算機看的,沒有分配內存,沒有具體的值。函數調用時寫的參數叫做實參,這些參數要有意義,即分配了內存,有具體的值
③函數參數傳遞過程中,值傳遞和引用傳遞區別
值傳遞是只把對象的值傳入函數,函數中可以使用這個值,但卻無法更改該對象的值
引用傳遞是將整個對象本身(或地址)傳入函數,在函數中既可調用對象的值,也可改變對象的值
2.編程實驗部分
2-28(1)
#include<iostream> using namespace std; int main() { cout << "Menu: A(dd) D(elete) S(ort) Q(uit),Select one:" << endl; while (true){ char c; cin >> c; if (c == 'A') { cout << "數據已經增加。" << endl; continue; } else if (c == 'D') { cout << "數據已經刪除。" << endl; continue; } else if (c == 'S') { cout << "數據已經排序。" << endl; continue; } if (c =='Q') break; return 0; } }
2-28(2)
#include<iostream> using namespace std; int main() { cout << "Menu: A(dd) D(elete) S(ort) Q(uit),Select one:" << endl; while (true){ char c; cin >> c; switch (c) { case 'A': cout << "數據已經增加。" << endl; continue; case 'D': cout << "數據已經刪除。" << endl; continue; case 'S': cout << "數據已經排序。" << endl; continue; case 'Q': return 0; } } }
2-29(一)判斷一個數為質數的算法:用一個循環找出這個數所有的因數,如果因數為2,即為1和它本身,則這個數是質數。
(二)(1)while 語句
#include<iostream> using namespace std; int main(){ int a,i=2,j; while (i<=100) { a=1,j=2; while (j<=i) { if (i%j == 0) { a++; }j++; } if (a==2){ cout << i << " "; } i++; } return 0; }
(2)for 語句
#include<iostream> using namespace std; int main() { int i, j, a; for (i = 2; i <=100; i++) { a = 1; for (j = 2; j <= i; j++){ if (i%j == 0) { a++; } } if (a == 2) { cout << i << " "; } }return 0; }
(3)do while 語句
#include<iostream> using namespace std; int main() { int i=2, j, a; do { a = 1, j = 2; for (j = 2; j <= i; j++) { if (i%j == 0) { a++; } } if (a == 2) { cout << i << " "; } i++; } while (i <= 100); return 0; }
2-32(1) while 語句
#include <iostream> using namespace std; int main() { int i,n=65;//n為要猜的數,可修改n的值 cout << "猜這個數:"; cin >> i; while (true) { if (i != n) { if (i < n) cout << "小了" << endl; else cout << "大了" << endl; } else { cout << "猜對了!"; break; } cin >> i; } return 0; }
(2)do while 語句
#include <iostream> using namespace std; int main() { int i, n = 65;//n為要猜的數,可修改n的值 cout << "猜這個數:"; cin >> i; do { if (i != n) { if (i < n) cout << "小了" << endl; else cout << "大了" << endl; } else { cout << "猜對了!"; break; } cin >> i; } while (true); return 0; }
2-34(一)思路:參照書例3-9,用遞歸法計算
(二)
#include <iostream> using namespace std; int comm(int n, int k){ if (k > n) return 0; else if (k == 0 || n == k) return 1; else return comm(n - 1, k) + comm(n - 1, k - 1); } int main(){ int n, k; n = 5; k = 3 ;//五種顏色,摸三次 cout << comm(n, k) << endl; return 0; }
實驗總結與體會
這次實驗花費的時間和精力都遠遠超過了上一次,上次還能仿寫,而這次大多是按照自己的想法來編的。
雖然花了很久,但也不是沒有收獲,循環語句用得挺熟練了,之間的轉化也是。
但欠缺的也很多,感覺自己寫的代碼還是有很多可以改進的地方的,但憑借現在的自己還是辦不到的。
還是希望經過一次次的練習自己的技術能夠更好吧。