实习任务一
1.3.1命名空间
(1)namespace xxx {
double fun(double a, double b) {
return a + b;
}
}
namespace yyy {
double fun(double a, double b) {
return (a + b) / 2;
}
}
#include <iostream>
using namespace std;
using namespace yyy;
int main() {
cout << fun(1, 4) << endl;
using xxx::fun;
cout << fun(1, 4) << endl;
cout << yyy::fun(1, 4) << endl;
return 0;
}
(2)重载特性 自动以形式参数选择函数
#include <iostream>
#include <string>
using namespace std;
string add(const string &s1, const string &s2) {
return s1 + s2;
}
double add(double a, double b) {
return a + b;
}
int main() {
cout << add("hello", "world") << endl;
cout << add(3, 5) << endl;
cout << add('3', '5') << endl;
return 0;
}
(3)
#include <iostream>
using namespace std;
int gcd(int m, int n) {
if (n == 0)
return m;
return gcd(n, m % n);
}
int main() {
cout << "1:" << gcd(20, 8) << endl;
cout << "2:" << gcd(36, 64) << endl;
return 0;
}
1.3.2实习任务二:
int temple;
for (int i = 0; i < size / 2; i++) {
temple = array[size - i - 1];
array[size - i - 1] = array[i];
array[i] = temple;
}
}
#include <iostream>
using namespace std;
int getMax(int *array, int size) {
int i = 0;
int f = *array;
for (i = 0; i < size; i++) {
if (f < * (array + i))
f = *(array + i);
}
return f;
}
int main() {
int size = 5;
int a[5] = {1, 2, 3, 4, 5};
int *array;
array = a;
cout << getMax(array, size);
return 0;
}