1.函数重载编程练习编写重载函数add(),实现对int型,double型,Complex型数据的加法
#include<iostream>
using namespace std;
struct complex{
double real;
double imaginary;
};
int add(int,int);
double add(double, double);
complex add(complex, complex);
int main(){
int x;
double y;
complex z;
int a,b;
cout<<"请输入两个整数:"<<endl;
cin>>a>>b;
x=add(a,b);
cout<<"整数之和为:"<<x<<endl;
double c,d;
cout<<"请输入两个double型数:"<<endl;
cin>>c>>d;
y=add(c,d);
cout<<"double类型之和为:"<<y<<endl;
complex e,f;
cout<<"请输入两个复数的实部虚部"<<endl;
cin>>e.real>>e.imaginary>>f.real>>f.imaginary;
z=add(e,f);
cout<<"复数之和为:"<<z.real<<"+"<<z.imaginary<<"i"<<endl;
return ;
}
int add(int a,int b)
{
return (a+b);
}
double add(double a,double b)
{
return (a+b);
}
complex add(complex a,complex b)
{
complex c;
c.real=a.real+b.real;
c.imaginary=a.imaginary+b.imaginary;
return c;
}
2.编写实现快速排序函数模板,并在main()函数中,定义不同类型数据,调用测试。
#include<iostream>
using namespace std;
void QuickSort(double ar[], int left ,int right)
{
if(left<right)
{
int i = left;
int j = right;
double x = ar[i];
while(i<j)
{
while(i<j&&ar[j]>x)
j--;
if(i<j)
{
ar[i] = ar[j];
i++;
}
while(i<j&&ar[i]<x)
i++;
if(i<j)
{
ar[j] = ar[i];
j--;
}
}
ar[i] = x;
QuickSort(ar, left, i-1);
QuickSort(ar, i+1, right);
}
}
int main()
{
int n = 10 ;
double ar[]={5,78,45,67,45,55,24,89,54,9};
int i;
cout<<"排序前的数为:";
for(i=0;i<n;++i)
cout<<ar[i]<<' ';
cout<<endl;
QuickSort(ar,0,n-1);
cout<<"排序后的数为: ";
for(i=0;i<n;++i)
cout<<ar[i]<<' ';
cout<<endl;
return 0;
}
3.写一个处理用户信息的类,可以打印信息,支持修改密码。
#include <iostream>
#include <string>
using namespace std;
class user
{public:
void setInfo(string name0,string password0="",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 old;
int i=;
cout<<"请输入原密码:"<<endl;
cin>>old;
while (old!=password && i<)
{i++;
cout<<"错误,请重新输入:"<<endl;
cin>>old;
}
if(old==password)
{cout<<"请输入新密码:"<<endl;
cin>>password;
}
else if(i=)
cout<<"请稍后再试"<<endl;
} void user::printInfo ()
{cout<<"name :"<<name<<endl;
cout<<"passwd : ******"<<endl;
cout<<"email :"<<email<<endl;
} int main()
{user user1;
user1.setInfo("Leonard");
user1.printInfo();
user1.changePassword();
user1.printInfo();
cout<<endl;
user user2;
user2.setInfo("Jonny","","xyz@hotmail.com");
user2.printInfo();
return ;
}