c++实验2

1、编写重载函数add()

#include <iostream>
using namespace std;
struct Complex
{double real;
 double imaginary;
};

int add(int x,int y)
{return x+y;
}
double add(double x,double y)
{return x+y;
}
Complex add(Complex x, Complex y)
{Complex s;
 s.real=x.real+y.real;
 s.imaginary=x.imaginary+y.imaginary;
 return s;
}
int main()
{int a,b;float c,d;Complex m,n;
 cout<<"输入2个整数:";
 cin>>a>>b;
 cout<<add(a,b)<<endl;
 cout<<"输入2个浮点数:";
 cin>>c>>d;
 cout<<add(c,d)<<endl;
 cout<<"分别输入2个复数的实部、虚部:";
 cin>>m.real>>m.imaginary>>n.real>>n.imaginary;
 cout<<add(m,n).real<<"+"<<add(m,n).imaginary<<"i"<<endl; 
return 0;
}

运行结果:

 

2、编写实现快速排序函数模板

#include <iostream>
using namespace std;

template <class T>
void quicksort(T a[],int low, int high)
{T key=a[low];
 int m=low,n=high;
 while(m<n)
 {if(low>=high)
     return;
  while(m<n)
  {while(a[n]>=key&&n>m)
        n--;
   if(m<n)
      {T t;
       t=a[n];a[n]=a[m];a[m]=t;
      }
   while(a[m]<=key&&m<n)
         m++;
   if(m<n)
      {T t;
       t=a[m];a[m]=a[n];a[n]=t;
      }
  }
  quicksort(a,low,m-1);
  quicksort(a,m+1,high);
 }
}
int main()
{int a[5]={42,56,20,80,11},i;
 double b[5]={33.3,88.8,90.6,45.2,18.9};
 quicksort(a,0,4);
 for(i=0;i<5;i++)
   cout<<a[i]<<" ";
 cout<<endl;
 quicksort(b,0,4);
 for(i=0;i<5;i++)
   cout<<b[i]<<" ";
} 

 

 运行结果:

 

3、设计并实现一个用户类User

#include <iostream>
#include <string>
using namespace std;
class user 
{public:
   void setInfo(string name0,string password0="111111",string email0=" ");
   void changePassword();
   void printInfo();
 private:
   string name;
   string password;
   string email;
};

void user::setInfo(string name0,string password0,string email0)
{name=name0;
 password=password0;
 email=email0;
}

void user::changePassword()
{string n; int i;
 cout<<"Enter the old passwd:";
 cin>>n;
 for(i=1;i<=2;i++)
    {if(n!="123456")
        {cout<<"passwd input error,Please re-enter again:";
         cin>>n;
        }
     else
         break;     
    }
 if(i==3)
   cout<<"Please try after a while."<<endl;
}

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.changePassword();
 user1.printInfo();
 cout<<endl<<"testing 2……"<<endl;
 user user2;
 user2.setInfo("Tim","92197","xyz@hotmail.com");
 user2.printInfo();
 return 0;
}

 运行结果:

 

实验总结与体会:

1、在热心同学的帮助下,找到了第2题的解决方法,参考了百度百科的快速排序。

2、学习了简单的类的定义、实现、使用

3、结构体在大一上学的太表面了,没有深入学习,望有大佬能为我指点迷津

4、实在没有大量的大块时间来给我思考,希望自己以后尽力而为吧。

我的评论:

1、https://www.cnblogs.com/sqcmxg/p/10574927.html

2、https://www.cnblogs.com/bzwy/p/10564202.html

3、https://www.cnblogs.com/zuiyankh/p/10587674.html

posted @ 2019-03-24 14:12  独倚泪静  阅读(192)  评论(1编辑  收藏  举报