1。
实验要求:编写重载函数add(),实现对int型,double型,complex型数据的加法。在main()函数中定义不同类型数据,调用测试。
#include<iostream> using namespace std; int add(int x, int y) { return x + y; } double add(double x, double y) { return x + y; } struct Complex { double real; double imaginary; }; Complex add(Complex a, Complex b) { cout << a.real + b.real << '+' << a.imaginary + b.imaginary << 'i' << endl; return a; } int main() { int h, t; cin >> h >> t; cout << add(h, t) << endl; double x, y; cin >> x >> y; cout << add(x, y) << endl; Complex a, b; cin >> a.real >> a.imaginary >> b.real >> b.imaginary; add(a, b); system("pause"); return 0; }
2.
实验要求:编写实现快速排序函数模板,并在main()函数中,定义不同类型数据,调用测试。
#include<iostream> using namespace std; template<typename T> int ks(T a[], int m, int n) { int i = m, j = n; T k = a[i]; int temp; while (i < j) { while (a[j] > k&&i < j) { j--; } if (i < j) { a[i] = a[j]; i++; } while (a[i] < k&&i < j) { i++; } if (i < j) { a[j] = a[i]; j--; } } a[i] = k; return i; } template<typename T> void qs(T a[], int m, int n) { if (m < n) { int q = ks(a, m, n); qs(a, m, q - 1); qs(a, q + 1, n); } } int main() { double a[5] = { 7,2.1,9,3,45.3 }; qs(a, 0, 4); int i; for (i = 0; i <= 4; i++) { cout << a[i]<<' '; } cout << endl; system("pause"); return 0; }
3.
实验要求:设计并实现一个用户类User,并在主函数中使用和测试这个类。每一个用户有用户名(name), 密码(passwd),联系邮箱(email)三个属性。 支持设置用户信息setInfo()。允许设置信息时密码默认为6个1,联系邮箱默认为空串。 支持打印用户信息printInfo()。打印用户名、密码、联系邮箱。其中,密码以6个*方式显示。 支持修改密码changePasswd()。在修改密码前,要求先输入旧密码,验证无误后,才允许修改。 如果输入旧密码时,连续三次输入错误,则提示用户稍后再试,暂时退出修改密码程序。 在main()函数中创建User类实例,测试User类的各项操作(设置用户信息,修改密码,打印用户信息)
#include<iostream> using namespace std; #include<string> class user { public: void setinfo(string na="Leonard",string pw="111111",string em=" "); void changePasswd(); void printInfo(); private: string name; string passwd; string email; }; void user::setinfo(string na, string pw, string em) { name = na; passwd = pw; email = em; } void user::changePasswd() { int a = 0, i = 0; string n, q; cout << "Enter the old passwd: "; cin >> n; while (1) { while (n != passwd) { cout << "passwd input error,Please re-Enter again:"; a = a + 1; cin >> n; if (a == 2) { cout << "please try after a while." << endl; break; } } break; } } void user::printInfo() { cout << "name: " << name << endl; cout << "passwd: " << "******" << endl; cout << "email: " << email << endl; } int main() { cout << "testing 1......" << endl; user user1; user1.setinfo("Leonard"); user1.printInfo(); user1.changePasswd(); user1.printInfo(); cout << endl << "testing 2......" << endl << endl; user user2; user2.setinfo("Jonny", "92197", "xyz@hotmail.com"); user2.printInfo(); system("pause"); return 0; }
1.第一题其实并没有太大的难度,相比较而言是三题中的热身题(but 我还是写了好几遍才过要反思反思)。
2.第二题的话是难度的确蛮大的,我们并不熟悉快速排序的算法。即使老师讲了也是半懂不懂。课上的话只能照葫芦画瓢没有搞定。反倒是在宿舍里仔细的看了快速排序的课件,反复推敲才理清思路。
3.第三题怎么说呢基本上除了类的定义和函数都给你了,只要自己补充一下就行。难度其实不大。
4.这次实验我觉得难度不错。至少我课上没有写完。写完三题以后感觉自己有点成就感(可能是基础不好吧)。