SYNU 22-23-2C++第四章(实验)

发布时间 2023-03-31 14:06:42作者: 粉色妖精小姐

仅展示答案以供参考,原题请见PTA

6-1 面积计算器(函数重载)

1 int area(int x,int y){
2     return x*y;
3 }
4 int area(int x,int y,int z){
5     return 2*(x*y+y*z+z*x);
6 }

 

6-3 最大值函数重载

 1 #include "iostream"
 2 using namespace std;
 3 int myMax(int a,int b){
 4     return (a>b)?a:b;
 5 }
 6 int myMax(int a,int b,int c){
 7     int max_ab=myMax(a,b);
 8     return (max_ab>c)?max_ab:c;
 9 }
10 double myMax(double a,double b){
11     return (a>b)?a:b;
12 }

 

6-4 函数重载实现两数相加

1 int add(int a,int b){
2     return a+b;
3 }
4 double add(double a,double b){
5     return a+b;
6 }
7 string add(string s1,string s2){
8     return s1+s2;
9 }

 

6-5 引用作函数形参交换两个整数

1 void Swap(int& a,int& b){
2     int temp=a;
3     a=b;
4     b=temp;
5 }

 

6-6 带默认形参值的函数

 
1 int add(int a,int b=20,int c=30){
2     return a+b+c;
3 }

 

6-7 逆序字符串

1 void reverse_string(string& str){
2     int left=0;
3     int right=str.size()-1;
4     while(left<right){
5         char temp=str[left];
6         str[left++]=str[right];
7         str[right--]=temp;
8     }
9 }

 

6-9 买一送一(引用传参、引用作为函数返回值)

1 float& cut(float &x,float &y){
2     if(x<y){
3         x=0;
4         return x;
5     }else{
6         y=0;
7         return y;
8     }
9 }