C++练习题库

1.矩阵类

Description
实现矩阵类matrix,行数和列数均不超过10
成员方法如下:
构造函数matrix(int m,int n):m为矩阵的行数,n为矩阵的列数,第i行第j列的元素赋值为按行优先顺序存放的元素的序号;
at(int, i)返回按行顺序优先的第i个元素
at(int i,int j):返回第i行第j列元素的值,注意和二维数组下标的差别。比如at(3,4)是矩阵的第3行第4列的元素,而非行标为3 列标为4的元素,在下面的示范数据中at(3,4)的结果为12。
sum():计算矩阵所有元素的和。
如3行4列矩阵构造为:
1 2 3 4
5 6 7 8
9 10 11 12

主函数如下:

int main()
{
int rowNum,colNum;
cin>>rowNum>>colNum;
matrix mat(rowNum,colNum);
cout< }

Input
行数和列数

Output
输出第4个元素的值,第3行第4列元素的值,所有元素的和,中间用空格隔开。

Samples
Input 复制
3 4
Output
4 12 78

#include
using namespace std;
class matrix {
	public://一般函数都写到public里面
		int at(int);
		int at(int,int);
		matrix(int m,int n) {//构造函数与类同名
			rownum=m;
			colnum=n;
			for(int i=1; i<=m; i++) {/*构造矩阵*/
				for(int j=1; j<=n; j++) {
					s[i][j]=at((i-1)*n+j);
				}
			}
		}
		int sum();//求和函数
	private:
		int rownum,colnum,s[15][15];//私有成员
};
int matrix::at(int x){
	return x;
}
int matrix::at(int x,int y){
	return this->s[x][y];
}

int matrix::sum(){
	int res=0;
	for(int i=1;i<=this->rownum;i++){
		for(int j=1;j<=this->colnum;j++)
			res+=this->s[i][j];
	}
	return res;
}
int main() {
	int r,c;
	cin>>r>>c;
	matrix mat(r,c);
	cout<<mat.at(4)<<" "<<mat.at(3,4)<<" "<<mat.sum();
	return 0;
}

C++练习题库_第1张图片
类其实相当于结构体,类可以拥有函数和变量。
this 是在类外面定义函数的时候一个自动的指针,指的就是调用这个函数的那个类的对象。
类和对象的总结

2.长方形类:

Description

定义长方形类rectangle,数据成员包括长length和宽width,均为double类型,成员函数包括:

(1)构造函数2个,一个无参的构造函数,长和宽的默认值为0,带两个参数的构造函数;

(2)设置长方形尺寸函数assign,即任意输入2个实数,大的数赋值给长,小的数赋值给宽

(3)计算长方形周长函数double circumference();

(4)计算长方形面积的函数double area();

(5)输出长方形的长和宽

要求在main函数中创建3个长方形的对象,第1,2个长方形分别由无参构造函数和有参构造函数初始化实现,第3个长方形对象通过输入数据,调用设置长方形尺寸函数,给长宽赋值,然后分别计算3个长方形的周长和面积,并输出结果

int main()

{

rectangle c1,c2(2.0,1.0),c3;

double x,y;

cin>>x>>y;

c3.assign(x,y);

… 其余代码自己填写…

    return 0;

}

Input
输入仅一行数据,输入2个实数,数据之间用空格分开

Output
3个长方形输出3行数据,每行数据先输出长方形的长、宽,再输出它对应的周长和面积,小数点后保留2位数字,一行中4个数据之间用逗号分隔

Samples
Input 复制
2.5 3.8
Output
0.00,0.00,0.00,0.00
2.00,1.00,6.00,2.00
3.80,2.50,12.60,9.50

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;

class rectangle{
	private:
		double x,y;
		
	public:
		rectangle()	{//无参构造函数,默认值为0
		  x=0;y=0;
		}
		 
		 rectangle(double x ,double y)//有参构造函数
		 {
		   this->x=x;
		   this->y=y;
		 }
		void assign (double x,double y)//设置长方形尺寸的函数,大的给长小的给宽
		{
			if(x>y)
			{
				this->x=x;
		        this->y=y;
			}
		  else
		  {
		  	this->x=y;
		  	this->y=x;
		  }
		}
		double circumference()//周长函数
		{
		  return 2*(x+y);
		}
		
	    double area()//面积函数
	    {
	      return x*y;
		}
		void display()//专门用于输出长和宽的函数
		{
			cout<<fixed<<setprecision(2)<<x<<' '<<y<<' ';
		}
	
		
};
int main()
{
	rectangle c1,c2(2.0,1.0),c3;//注意:一般对于c2(2.0,1.0)就是有参构造函数,所以在类里面对于构造函数时要记得写形参,即rectangle(double x ,double y)
    double x,y;
    cin>>x>>y;
    c3.assign(x,y);
    c1.display();
    cout<<fixed<<setprecision(2)<<c1.circumference()<<","<<c1.area()<<endl;
    c2.display();
    cout<<fixed<<setprecision(2)<<c2.circumference()<<","<<c2.area()<<endl;
    c3.display();
    cout<<fixed<<setprecision(2)<<c3.circumference()<<","<<c3.area()<<endl;
   return 0;
}

3.圆柱体类

Description
定义圆柱体类cylinder,要求具有以下成员:半径 高

成员函数如下:

默认构造函数:半径和高设置为1

构造函数:其参数包括半径和高两个参数。

volume函数:返回圆柱体的体积;

area函数:计算圆柱体的表面积数据均为double PI的值取3.14

int main()
{

double radius,height; 

cin>>radius>>height; 
cylinder cylinder1,cylinder2(radius,height); 
cout<

}

Input
录入圆柱体的半径和高。

Output
见main函数

Samples
Input 复制
2 3
Output
3.14 12.56 37.68 62.80

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
const double PI=3.14;

class cylinder {
   public:
   	double r,h;
   	
   public:
   	
   	cylinder()
   	{
   	  r=1;h=1;
	}
   	cylinder(double r,double h)
   	{
   	  
   	  this->r=r;
   	  this->h=h;
	}
	double volume(){
		return PI*r*r*h;
	}
	double area(){
		return 2*PI*r*h+PI*r*r*2;
	}
	
};

int main()
{
	double radius,height; 
    cin>>radius>>height; 
    cylinder cylinder1,cylinder2(radius,height);
    cout<<fixed<<setprecision(2)<<cylinder1.volume()<<' '<<cylinder1.area()<<' '<<cylinder2.volume()<<' '<<cylinder2.area();; 
   return 0;
 }

4.盒子类

Description
定义盒子Box类,要求具有以下成员:长、宽、高分别为x,y,z,可设置盒子形状;可计算盒子体积;可计算盒子的表面积。

定义盒子Box类,要求具有以下成员:盒子的长、宽、高(x,y,z),数据均为整型;初始化类成员的带参构造函数;计算盒子体积的成员函数volumn;计算盒子的表面积的成员函数area。

Input
按顺序分别录入盒子的长、宽、高

Output
输出盒子的体积和表面积。中间用空格隔开。

Samples
Input 复制
3 4 5
Output
60 94

在这里#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
class Box{
   private:
   	int a;
   	int b;
   	int c;
   	ll v,s;
   	
   	public:
   	void InitBox(int x,int y,int z);
   	void volumn();
   	void area();
   	void show();
};
void Box::InitBox(int x,int y,int z)
{
   a=x;b=y;c=z;
   return;
}
void Box::volumn(){
	v=a*b*c;
}
void Box::area(){
	s=2*(a*b+a*c+b*c);
}
void Box::show(){
   cout<<v<<" "<<s;
   return;
}
int main()
{
	int a,b,c;Box box;
	cin>>a>>b>>c;
	box.InitBox(a,b,c);
	box.volumn();
	box.area();
	box.show();
   return 0;
   }

5.学生类

(输出输入的信息)
Description
编写程序,定义student类,并声明私有数据成员如下:num(学号 字符串),name(姓名)和三门课的成绩sumScore,总分
,建立成员函数如下:
构造函数:五个参数分别为学号,姓名和三门课的成绩
计算三门课的总成绩sum函数,总成绩放入sumScore数据成员。
显示学生的所有数据信息,各信息之间空格隔开。display()函数

Input
学生的学号,姓名和三门课的成绩

Output
学生的学号,姓名,三门课的成绩,总成绩,中间用空格隔开。

Samples
Input 复制
0100 zhangling 80 90 100
Output
0100 zhangling 80 90 100 270

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
class Stu{
   private://定义以下五个私有成员
   	string a;
   	string b;
   	int c;
   	int d;
    int e;
    
    public:
    int sumScore(int c,int d,int e)//计算总分的函数,此处需要形参
    {
      int ans=c+d+e;
      cout<<ans;
	}
	void display(string a,string b,int c,int d,int e)//输出输入的所有信息并且输出总分,此处需要形参
	{
	  cout<<a<<' '<<b<<' '<<c<<' '<<d<<' '<<e<<' ';
	}
};
int main()
{
	string a,b;
	int c,d,e;
	cin>>a>>b>>c>>d>>e;
	Stu q;//相当于给该类起个名字成为q;
	q.display(a,b,c,d,e);//注意只要调用类里面的函数都需要"类名."的形式进行调用
	q.sumScore(c,d,e); 
   return 0;
}

6.student类

Description
定义student类,私有数据成员包括:stuNum(学号 字符串),stuName(姓名 字符串)和高数、英语和程序设计三门课的成绩,总成绩,成绩均为整型,成员函数包括:
(1)构造函数2个,一个含2个参数,分别为学号,姓名,成绩都默认为0;另一个含学号、姓名和三门课的成绩,总分默认为0

(2)计算三门课的总成绩函数,函数名统一用sumfun

(3)显示学生信息函数,各信息之间用空格隔开,函数名统一用display

(4)输入学生三门课成绩的函数,函数名统一用inputscore

要求在main函数中创建2个学生对象,第1个对象需要用inputscore函数输入三门课成绩,第2个学生对象由参数给出成绩,然后计算出2个学生的总分,最后输出这2个学生的信息。main函数部分代码如下:

int main()

{

student st1(“111”, “John”), st2(“222”,“Mike”,67,89,92) ;

…. // 请补充 其他代码

return0;

}
Input
三门课的成绩,成绩用空格分开
Output
输出学生的各信息,按学号、姓名、高数成绩、英语成绩、程序设计成绩以及总成绩,每一个数据之间用空格隔开,每个学生的信息占一行。
Samples
Input 复制
75 86 96
Output
111 John 75 86 96 257
222 Mike 67 89 92 248

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
class student{
	
	private://定义私有成员
		string s1;
		string s2;
		int math;
		int english;
		int techo;
		int sum;
	public:
		student(string sr1,string sr2){//定义构造函数含两个参数,成绩默认均为0
			s1=sr1;
	        s2=sr2;
        	math=0;
	        english=0;
	        techo=0;
	        sum=0;
		}
		student(string sr1,string sr2,int x,int y,int z){//定义构造函数,总分默认为0
			s1=sr1;
	        s2=sr2;
        	math=x;
        	english=y;
	        techo=z;
	        sum=0;
		}
		void sumfun(){/
			int ans=math+english+techo;
			sum=ans;
		}
		void display(){//一般如果主函数里有实参那么类里面对应的函数也应该有形参
			cout<<s1<<" "<<s2<<" "<<math<<" "<<english<<" "<<techo<<" "<<sum<<endl;
		}
		void inputscore(){//输入函数,用于输入三科成绩
			int a,b,c;
	        cin>>a>>b>>c;
	        math=a;
	        english=b;
        	techo=c;
		}
};

int main(){
  student st1("111", "John"),               st2("222","Mike",67,89,92) ;
	st1.inputscore();
	st1.sumfun();
	st1.display();
	st2.sumfun();
	st2.display();
	return 0;
}

7.teacher 类

程序在线评测平台(Programming Online Judge Platform)
主页
状态
题库
竞赛
排名
IWSXQY
注册帐号请注意
概览
状态
榜单 [ acm ]
告示
O . teacher类
Description
定义teacher类,私有数据成员包括:jobNO(工号 字符串),Name(姓名 字符串)和基本工资(base_pay),补贴(allowance), 保险金(insurance),工资总和,实发工资,均为double型,成员函数包括:

(1)构造函数2个,一个含2个参数,分别为工号,姓名,其他值都默认为0;另一个含工号、姓名和基本工资、补贴、保险金,工资总和与实发工资的值默认为0

(2)计算应发工资和实发工资的函数,函数名统一用salary。

工资总和=基本工资+补贴; 实发工资=工资总和—保险金

(3)显示教师信息函数,各信息之间用空格隔开,函数名统一用display

(4)输入教师基本工资、补贴、保险金的函数,函数名统一用input

要求在main函数中创建2个教师对象,第1个对象需要用input函数输入基本工资、补贴、保险金,第2个教师对象由参数给出基本工资、补贴、保险金,然后计算出2个教师的工资总和及实发工资,最后输出这2个教师的信息。main函数部分代码如下:

int main()

{

teacher t1(“111”, “Mary”),t2(“222”,“Alex”,4256.78,1234.56, 895.17) ;

…. // 请补充 其他代码

return0;

}

Input
输入基本工资、补贴、保险金的金额,用空格分开

Output
输出教师的信息,按工号、姓名、基本工资、补贴、保险金、工资总和、实发工资,每一个数据之间用空格隔开,每个教师的信息占一行。

Samples
Input 复制
6589.45 1549.21 985.47
Output
111 Mary 6589.45 1549.21 985.47 8138.66 7153.19
222 Alex 4256.78 1234.56 895.17 5491.34 4596.17

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
class teacher{
	private:
		string jobNo;
		string Name;
		double base_pay;
		double allowance;
		double insurance;
		double sum;
		double shifa;
	public:
		teacher(string j,string n){
			jobNo=j;
			Name=n;
			base_pay=0;
			allowance=0;
			insurance=0;
			sum=0;
			shifa=0;
		}
		teacher(string j,string n,double x,double y,double z ){
			jobNo=j;
			Name=n;
			base_pay=x;
			allowance=y;
			insurance=z;
			sum=0;
			shifa=0;
		}
		void salary()
		{
			sum=base_pay+allowance;
			shifa=sum-insurance;
		}
		void display()
		{
			cout<<jobNo<<' '<<Name<<' '<<base_pay<<' '<<allowance<<' '<<insurance<<' '<<sum<<' '<<shifa<<'\n';
		}
		void input(){
			double a,b,c;
			cin>>a>>b>>c;
			base_pay=a;
			allowance=b;
			insurance=c;
		}
};
int main()
{
	teacher t1("111", "Mary"),t2("222","Alex",4256.78,1234.56, 895.17) ;
	t1.input();
	t1.salary();
	t1.display();
	t2.salary();
	t2.display();
	
   return 0;
 } 

8.专业类

Description
设计一个关于专业(my_major)的类,需要描述专业的名字(无空格),专业的学生人数,专业的老师的人数。
成员函数包括:
默认的构造函数:字符串类型的成员变量设置为空格,数值型的成员设置为0。
构造函数:分别为专业名,学生人数以及老师人数赋值。
显示专业信息函数:分别显示专业名,学生人数以及老师人数,不同的成员之间用空格隔开。

Input
专业名、学生人数、老师人数。

Output
用显示专业信息函数显示输入成员构造对象的信息和用默认构造函数构造的对象信息。

Samples
Input 复制
computer 3000 30000
Output
computer 3000 30000
0 0

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;

class my_major{
   
   private:
   	string s1;
   	int a;
   	int b;
   	
   public:
   	my_major()//构造无参构造函数
   	{
   	 this->s1=" ";
   	 this->a=0;
   	 this->b=0;
	}
	
	my_major(string s1,int a,int b)//构造有参构造函数
	{
	   this->s1=s1;
	   this->a=a;
	   this->b=b;
	}
	
	void display(string s,int a1,int b1)//用于输出的函数
	{
	  cout<<s1<<' '<<a<<' '<<b<<'\n';
	}
};
int main()
{
	string s;
	int a1,b1;
	cin>>s>>a1>>b1;
	my_major C1,C2(s,a1,b1);
	C2.display(s,a1,b1);
	C1.display(s,a1,b1);
	
   return 0;
}

9.复数类

Description

定义一个复数类complex,数据成员包括实部real和虚部imag,均为double类型。成员函数包括:

(1) 默认构造函数(即无参的构造函数),实部和虚部分别赋值为1.0,1.0 ;

(2) 带两个参数的构造函数(假设实参值是1.5,2.8);

(3) 输出复数的函数display, 输出格式为 实部+虚部i,例如: 1.00+1.00i ;

(4) 输入复数的函数input, 从键盘输入复数的实部和虚部;

(5) 计算复数的模的函数magnitude(函数返回值为double型),即对于复数 z=a+bi,它的模 |z|=sqrt(a2+b2)。

要求在main函数中创建3个复数对象,第1个复数的实部和虚部用input函数从键盘输入,第2、3个复数分别由用默认构造函数和带参数的构造函数实现初始化,最后分别输入这3个复数以及它们的模。

int main()

{

complex val1,val2,val3(1.5,2.8);

 val1.input();

val1.display();

cout<<"  "<

}

Input
输入复数的实部和虚部,两个实数之间用空格分开

Output
3个复数应输出3行数据,每行输出数据分两部分,先输出复数,再输出该复数的模,复数和它的模之间用2个空格分隔,所有实数小数点后保留两位

Samples
Input 复制
1.0 2.0
Output
1.00+2.00i 2.24
1.00+1.00i 1.41
1.50+2.80i 3.18

#include
#include
#include
using namespace std;
class complex
{
	public:
	complex(){
		real=1.0;
	    imag=1.0;
	}
	complex(double real,double imag){
		this->real=real;
		this->imag=imag;
	}
	void input(){
		cin>>real>>imag;
	}
	void display();
	double magnitude(){
		return sqrt(real*real+imag*imag);
	}
	private:
	double real;
	double imag;
};

void complex::display()
{
	if(real==0)
	{
		cout<<fixed<<setprecision(2)<<imag<<"i";
	}
	if(imag==0)
	{
		cout<<fixed<<setprecision(2)<<real;
	}
	if(imag<0)
	{
		cout<<fixed<<setprecision(2)<<real<<imag<<"i";
	}
	else
	{
		cout<<fixed<<setprecision(2)<<real<<"+"<<imag<<"i";
	}
}
int main()
{

    complex val1,val2,val3(1.5,2.8);

     val1.input();

    val1.display();

    cout<<"  "<<fixed<<setprecision(2)<<val1.magnitude()<<endl;

     val2.display();

    cout<<"  "<<val2.magnitude()<<endl;

     val3.display();

    cout<<"  "<<val3.magnitude()<<endl;

     return 0;  

}


10.字符串反转

Description
编写函数完成字符串反转。要求必须使用C++字符串,必须使用函数

Input
输入有多行,每一行代表一个字符串。 输入行数不确定,以ctrl+z结束。

Output
输出翻转后的字符串。每个字符串占一行。

Samples
Input 复制
who’s your daddy
my daddy is Li Gang
Output
yddad ruoy s’ohw
gnaG iL si yddad ym
Hint
对于多行判断,可采用while(getline(cin, str))来实现,如果getline获取到ctrl+z,则退出while循环。

#include
using namespace std;
string ReversetString(string input)//字符串反转函数
{
   string b=input;
   int len=0,i=0;
   while(input[i++]!='\0')
   len++;
   i=0;
   while(input[i]!='\0')
   b[(len--)-1]=input[i++];
   return b;
}
int main()
{
	  string str;
	  while(getline(cin,str)){
	  string s=ReversetString(str);
	  if(str=="Ctrl+Z")
	  break;
	  else
	  cout<<s<<endl;
	}
    return 0;
}

11.六边形

Description
六边形类包括成员函数如下:
hexagons(double sideValue=10);边长设置为默认值10
double circumference();周长函数
double area();面积函数
void setSide(double sideValue);设置边长
double getSide();读边长
类成员自定
主函数如下:

int main()
{
double side;
cin>>side;
class hexagons hex1;
cout<<"The side of the hxagons is "hex1.getSide()< hex1.setSide(side);
cout<<"The circumference of the hex1 is “<

return 0; 

}

Input
边长

Output
输出其边长,以及周长和面积

Samples
Input 复制
5
Output
The side of the hxagons is 10
The circumference of the hex1 is 30 and area is 64.9519

#include
using namespace std;
typedef  long long ll;
const int maxn=1e5+9;

class hexagons {
    private:
   	double sideValue;
   	
   	public:
   	hexagons()
   	{
   	  sideValue=10;//无参构造函数,边长默认值为10
	}
	double circumference()
	{
		return 6*sideValue;
	}
	double area()
	{
	   return (3*sqrt(3)*sideValue*sideValue)/2.;
	}
	double setSide(double sideValue)//设置边长函数
	{
	   this->sideValue=sideValue;
	}
	double getSide()
	{
		return sideValue=10; //读边长函数
	}
};
int main()
{
double side;
 cin>>side;
 class hexagons hex1;
 cout<<"The side of the hxagons is "<<hex1.getSide()<<endl;
 hex1.setSide(side);
 cout<<"The circumference of the hex1 is "<<hex1.circumference()<<" and area is "<<hex1.area()<<endl;
	
   return 0;
}

12. 日期转换

Description
声明一个类,有数据成员年,月,日,建立两个成员函数:

构造函数:输入年,月,日初始化日期

int orderOfYear():计算所输入日期在本年中是第几天,注意闰年问题。

Input
按年,月,日输入三个整数

Output
一年中的第几天

Samples
Input 复制
2013 3 1
Output
60

#include 
#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;

struct Date{
	int year;
	int month;
	int day;
}date;
const int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
bool isLeapYear(int year){
	return year%4==0 && year%100!=0 || year%400==0;
}
int main(){
	cin>>date.year>>date.month>>date.day;
	int sum = 0;
	for(int i=0;i+1<date.month;i++) sum += days[i];
	sum += date.day;
	if(date.month>2 && isLeapYear(date.year))sum++;
	cout<<sum; 
	return 0;
} 

13.数组类

Description
建立模板数组类:array
成员方法如下:
array(int n);其中n用来设置数组元素的个数
~array();
int sizeOfArray();返回数组中元素的个数
重载 operator[](int index),返回下标为index的数组元素。
定义setElement()函数 ,该函数有2个参数,其中第一个参数为数组元素的下标,第二个参数为数组元素的值。

Input
输入有3行,第1行输入模板数组类型,其中1代表建立整数数组类, 2代表建立double数组类,3代表char数组类;
第2行输入数组中元素的个数;
第3行输入数组中各个元素.

Output
输出数组中各元素,元素之间用一个空格分开,注意最后一个元素后没有空格

Samples
Input 复制
1
3
1 2 3
Output
1 2 3

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;


int main()
{
	
	int x,n;
	cin>>x>>n;
	if(x==1)
	{
	  int a[10100];
	  for(int i=0;i<n;i++)
	  {
	    cin>>a[i];
	  }
	  for(int i=0;i<n;i++)
	  {
	    cout<<a[i]<<' ';
	  }
	}
	else if(x==2)
	{
	   double b[10100];
	   for(int j=0;j<n;j++)
	   {
	     cin>>b[j];
	   }
	   for(int j=0;j<n;j++)
	   {
	     cout<<b[j]<<' ';
	   }
	}
	else if(x==3){
		char c[10100];
		for(int k=0;k<n;k++)
		{
		   cin>>c[k];
		}
	for(int k=0;k<n;k++)
		{
		   cout<<c[k]<<' ';
		}
	}
	
	
   return 0;
}

本题该写法只是过了测试数据,并非C++写法

14.简单point类

Description
定义类point,其中包括两个数据成员,均为 int 类型,为点的横坐标和纵坐标。

类的成员函数如下:

构造函数:包括两个参数,其两个参数的默认值为0。

重载运算符 +、-

+:两个点相应的坐标相加,比如(1,1)+(2,2)=(3,3)

-:两个点相应的坐标相减,比如(2,2)-(1,1)=(1,1)

输出函数output,输出点的横坐标和纵坐标如下:(2,3)其中2为横坐标,3为纵坐标

输入函数input,:输入点的横坐标和纵坐标,中间以空格隔开比如输入2 3 ,给点的横坐标和纵坐标赋值.

Input
分别输入两个点的横坐标和纵坐标, 中间空格隔开

Output
第1行输出 x,y 两点之和,第2行输出x,y 两点之差

Samples
Input 复制
3 4
1 2
Output
(4,6)
(2,2)

#include
using namespace std;
class point {
	private: 
	int x;
	int y;
	public:
		point (int a=0,int b=0):x(a),y(b){}
	void set(int a,int b){
		x=a,y=b;
	}
	friend point add(const point& left,const point& right);
	friend point sub(const point& left,const point& right);
	void show(){
		
		cout<<"("<<x<<','<<y<<")"<<"\n";
	}
};
point add(const point& lt,const point& rt){
	return point(lt.x+rt.x,lt.y+rt.y);
}
point sub(const point& lt,const point& rt){
	return point(lt.x-rt.x,lt.y-rt.y);
}
int main(){
	int a,b,c,d;
	cin>>a>>b>>c>>d;
	point x1,x2,ans;
	x1.set(a,b);
	x2.set(c,d);
	ans=add(x1,x2);
	ans.show();
	ans=sub(x1,x2);
	ans.show();
	return 0;
}

15.shape类

Description
编写图形类shape,其中包含数据成员color(string类型),表示图形的颜色;编写带参构造函数,初始化成员color;编写成员函数display,输出shape的基本信息。

编写派生类cylinder,包含数据成员圆半径radius和高度length(double类型);带参构造函数,初始化其成员;编写成员函数display,输出cylinder的基本信息。

编写派生类sphere,包含圆半径radius(double类型);编写带参构造函数,初始化其成员;成员函数display,输出cylinder的基本信息。

完成以上三个类,使下列主函数能够正确运行。

int main()

{

   string color;

   double x, y, z;

   cin >> color;

   cin >> x >> y >> z;

   shape s(color);

   cylinder c(color, x, y);

   sphere s1(color, z);



   s.display();

   c.display();

   s1.display();

}

在shape类中添加纯虚函数volume,cylinder和sphere也分别添加虚函数volume(),该函数用于计算体积。完成上述功能,使下列主函数能够正确运行。(注,pi取3.14,使用double类型进行计算)

#include “iomanip”

int main()

{

   shape *p;

   int x;

   cin >> x;

   if (x == 1)

   {

          double r, l;

          string color;

          cin >> color >> r >> l;

          p = new cylinder(color, r, l);

          cout << fixed << setprecision(2) << p->volume() << endl;

          delete p;

   }

   else if (x == 2)

   {

          double r;

          string color;

          cin >> color >> r;

          p = new sphere(color, r);

          cout << fixed << setprecision(2) << p->volume() << endl;

          delete p;

   }

}

Input
一个整数,表示选择生成的图形;一个字符串表示颜色,一个小数表示半径,一个小数表示高(图形为球是不需要)。

Output
图形的体积

Samples
Input 复制
1 red 1.2 2.2
Output
9.95

#pragma GCC optimize(2)
#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
# define PI 3.14
class shape{
	public:
		char name[100];
		int a;
	void setn(int b){
		a=b;
	}
	void setname(char s[100]){
		strcmp(name,s);
	}
	
};
class cylinder:public shape{
	public:
		double r,h;
	void setr(double rr,double hh){
		r=rr;h=hh;
	}
	void display(){
		double ans=(PI*r*r)*h;
		printf("%.2lf",ans);
	}
};
class sphere:public shape{
	public :
		double r;
	void setr(double rr){
		r=rr;
	}
	void display(){
		double ans=(4*r*r*r*PI)/3.;
		printf("%.2lf",ans);
	}
};
int main(){
	shape yuan;
	cylinder zp2;
	sphere zp3;
	int n;
	double r,h;
	char s[100];
	cin>>n>>s;
	yuan.setn(n);
	yuan.setname(s);
	if(n==1){
		cin>>r>>h;
		zp2.setr(r,h);
		zp2.display();
	}
	else if(n==2){
		cin>>r;
		zp3.setr(r);
		zp3.display();
		}
	return 0;
}

16.动态内存分配求整型数组元素之和

Description
编程输入数组元素的个数n,0

Input
输入有2行,第1行为一个整数,即数组元素个数,第2行依次输入数组元素的值,每个数据之间用空格分开

Output
输出有2行,第1行输出数组元素的值,第2行输出元素之和,具体格式见Sample Output

Samples
Input 复制
3
1 2 3
Output
a[3]={1,2,3}
sum=6

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
int a[10100];
int main()
{
	ll n,sum=0;
	cin>>n;
	int new a[10100];
	for(int i=0;i<n;i++)
	{
	  cin>>a[i];
	  sum+=a[i];
	}
	cout<<"a"<<"["<<n<<']'<<"="<<"{";
	for(int i=0;i<n;i++)
	{
	  if(i==n-1) {cout<<a[i]<<"}";break;
	  }
	  else  cout<<a[i]<<',';
	}
	cout<<'\n';
	cout<<"sum"<<"="<<sum;
   return 0;
}

17.动态内存分配求整型数组元素之和

Description
首先输入数组元素的个数n,0

Input
输入有2行,第1行为一个整数,即数组元素个数,第2行依次输入数组元素的值,每个数据之间用空格分开

Output
输出有2行,第1行输出原数组的元素,第2行输出替换后的数组元素,具体格式见Sample Output

Samples
Input 复制
5
2 -3 6 -8 9
Output
a[5]={2,-3,6,-8,9}
a[5]={2,0,6,0,9}

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
int a[10100];
int main()
{
	ll n,sum=0;
	cin>>n;
	for(int i=0;i<n;i++)
	{
	  cin>>a[i];
	  sum+=a[i];
	}
	cout<<"a"<<"["<<n<<']'<<"="<<"{";
	for(int i=0;i<n;i++)
	{
	  if(i==n-1) {cout<<a[i]<<"}";break;
	  }
	  else  cout<<a[i]<<',';
	}
	cout<<'\n';
	cout<<"a"<<"["<<n<<']'<<"="<<"{";
	for(int i=0;i<n;i++)
	{
		if(a[i]<0){
			cout<<"0"<<',';
		}
		else{
			if(i==n-1) {cout<<a[i]<<"}";break;
	  }
	  else  cout<<a[i]<<',';
		}
	  
	}
	cout<<'\n';
	
	
	
    return 0;
}

18.删除字符串的子串

29 . 删除字符串中的子串
Description
编写函数,去掉str字符串中出现的substr字符串。要求实参和形参之间按引用传递

若str字符串为aaas1kaaas,substr字符串为aaa,则输出结果s1ks。

Input
第一行有一个正整数T,表示测试数据的组数。后跟T组测试数据,每组测试数据占两行,第一行是字符串str,第二行是字符串substr。

Output

对于每组测试数据,输出结果占一行,即去掉substr后的str。

Samples
Input 复制
2
aaas1kaaas
aaa
zhangwangli
an
Output
s1ks
zhgwgli

#include
using namespace std;
typedef long long ll;
string str,str2;

int main()
{
	string str,str2;
	int t,n;
	cin>>t;
	while(t--){
		cin>>str;
		cin>>str2;
		string s1;
		int len=str.size();
		for(int i=0;i<len;i++){
			s1=str[i];
			for(int j=1;j+i<len;j++){
				s1+=str[i+j];
				if(str2==s1) {
					str.erase(i,j+1);
					break;
				}
			}
		}
		cout<<str<<endl;
	} 
   return 0;
}

19.交通工具类

Description
定义交通工具类(vehicle),成员包括编号,颜色. 成员函数包括构造函数,包括两个参数分别对成员进行赋值,display()用于显示成员的值.
定义交通工具类的子类自行车类(bike),成员包括编号,颜色,重量(weight整型),重写display()函数显示其所有成员值.

主函数如下:

int main()
{
int ID;
string name;
int weight;

cin>>ID>>name;

class vehicle vehicle1(ID,name);
vehicle1.display();
cout< cin>>ID>>name>>weight;
class bike bike1(ID,name,weight);
bike1.display();
cout<

return 0; 

}

Input
输入交通工具对象的编号,名称

输入自行车的编号,名称,重量

Output
输出交通工具的信息

输出自行车的信息

Samples
Input 复制
1 vehicle1
2 bike1 30
Output
vehicleID=1 vehicleName=vehicle1
vehicleID=2 vehicleName=bike1 weight=30

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;

class vehicle
{
protected:
    int ID;
    string name;
    
public:
	
    vehicle(int id=0,string s="")//这个可以写成vehicle(int id=0,string s=''):ID(id),name(s){}; 
	{
		ID=id;
		name=s;
	}
    void display()
    {
        cout<<"vehicleID="<<ID<<" vehicleName="<<name;
    }
};
class bike:public vehicle
{
private:
    int weight;
public:
    bike(int id=0,string s="",int w=0):vehicle(id,s),weight(w){};
    void display()
    {
        cout<<"vehicleID="<<ID<<" vehicleName="<<name<<" weight="<<weight;
    }
};
int main()
{
    int ID;
    string name;
    int weight;
    cin>>ID>>name;
    class vehicle vehicle1(ID,name);
    vehicle1.display();
    cout<<endl;
    cin>>ID>>name>>weight;
    class bike bike1(ID,name,weight);
    bike1.display();
    cout<<endl;
    return 0;
}

20.max_arr

Description

编写函数模板max_arr,返回数组的最大元素。数组元素可以为任意数据类型。完成上述功能,是下列主函数能够正确执行。

int main()

{

   int i_arr[10];

   char c_arr[10];

   string s_arr[10];

   int n;



   cin >> n;

   input(i_arr, n);

   cout << max_arr(i_arr, n) << endl;



   cin >> n;

   input(c_arr, n);

   cout << max_arr(c_arr, n) << endl;



   cin >> n;

   input(s_arr, n);

   cout << max_arr(s_arr, n) << endl;

}

Input
输入数据为一行,第一个为正整数n(n<=10),表示数组元素的数目,其余为数组元素

Output
数组的最大元素

Samples
Input 复制
5 1 2 3 4 5
3 b c a
4 red blue yellow green
Output
5
c
yellow

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
template <class arry> 
void input(arry *b,int len)
    {
        for(int i = 0; i < len; i ++)
            cin>>b[i];
    }
template <class arry> 
void max_arr(arry *b,int len)
    {
        for(int i=1;i<len;i++){
        	if(b[i]>b[0]) b[0]=b[i]; else b[0]=b[0];
		}
		cout<<b[0]<<endl;
        
    }
int main()
{
	int i_arr[10];
    char c_arr[10];
    string s_arr[10];
    int n;
	cin >> n;
    input(i_arr, n);
    max_arr(i_arr, n);
    cin >> n;
    input(c_arr, n);
    max_arr(c_arr, n);
    cin >> n;
    input(s_arr, n);
    max_arr(s_arr, n);
}

21.组件类

Description
定义件组件类(component),成员包括组件号(整型),组件名。 成员函数包括构造函数,包括三个参数分别对成员进行赋值,output()用于显示成员的值.
定义component类的子类外设类(device),成员包括除了父类的成员外,还包括生产厂家,进价,销售价(整数型),重写output()函数显示其所有成员值.

Input
录入组件对象的组件号,组件名

录入外设对象的组件号,组件名,进价,销售价,生产厂家

Output
输出组件对象的组件号,组件名

输出外设对象的组件号,组件名,进价,销售价,生产厂家

Samples
Input 复制
1 lingjian1
2 lingjian2 100 150 lianxiang
Output
1 lingjian1
2 lingjian2 100 150 lianxiang

#include 
using namespace std; 
typedef long long ll;
const int maxn=1e5+9;

class component //构造父类component 
{ 
   protected: 
   int a; 
   string name; 
   public: 
   component(int x=0,string s=""):a(x),name(s){}; 
   void output() 
    { 
    cout<<a<<" "<<name<<'\n'; 
    } 
}; 
class device:public component //构造子类device 
{ 
   private: 
   string changjia; 
   int jj,ss; 
     public: 
     device(int x,string s="",int y=0,int z=0,string s_=""):component(x,s),changjia(s_),jj(y),ss(z){}; 
    void output() { 
     cout<<a<<" "<<name<<" "<<jj<<" "<<ss<<" "<<changjia<<'\n'; 
} 
}; 
int main() 
{ 
int x; 
string s; 
cin>>x>>s; 
component a(x,s); 
a.output(); 
int y,z; 
string ss; 
cin>>x>>s>>y>>z>>ss; 
device b(x,s,y,z,ss); 
b.output(); 
return 0; 
}

22.图像的继承

Description
点类point
成员变量包括其横坐标x和纵坐标y。均为double类型。
构造函数,参数列表为x值和y值
display函数,显示形式如(1,2)其中1和2为点的横坐标和纵坐标。

对称图形类figure:
成员变量包括其图形的中心点。
构造函数,参数列表为point类型的对象。
display函数,在屏幕上显示其成员,显示形式如"I am a figure. The center is: (1,2)"。

图形圆类circle:
说明:circle是figure的子类。
成员变量包括:中心点,半径。
成员方法如下:
circle(point p,double r):构造函数
move(point p):函数的功能为把中心点移至p。
display();在屏幕上显示其成员,显示形式如"I am a circle, the center is: (1,2), the radius is: 2."

矩形类rectangle:
说明:rectangle是figure的子类。
成员变量包括:中心点,长度,宽度。
成员方法如下:
rectangle (point p,double lengthVal,double widthVal):构造函数
display();在屏幕上显示其成员,显示形式如"I am a rectangle, the center is: (1,2), the length is: 1, the width is: 2."

主函数如下:

int main()
{
double x,y,radius,width,length;
cin>>x>>y;
point p(x,y);
p.display();
cout< cin>>radius;
circle cir1(p,radius);
cir1.display();
cout< cin>>length>>width;
rectangle rectangle1(p,length,width);
rectangle1.display();
cout< return 0;

}

Input
录入一个点的横坐标和纵坐标.

Output
输出点。
输出圆。
输出矩形。

Samples
Input 复制
1 2
5
10 20
Output
(1,2)
I am a circle, the center is: (1,2), the radius is:5.
I am a rectangle, the center is: (1,2), the length is: 10, the width is: 20.

#include 
using namespace std; 
typedef long long ll;
const int maxn=1e5+9;


class point //定义类point 
{ 
   public: 
   double x,y; 
   point(double xx=0,double yy=0){//构造函数 
   	x=xx;y=yy;
   } 
   void display() //输出函数 
{ 
cout<<"("<<x<<","<<y<<")"; 
} 
}; 


class figure //构造类figure 
{ 
protected: 
double x_center;
double y_center; 
public: 
figure(double x_center=0,double y_center=0){}; //构造函数 
figure(point a) 
{ 
x_center=a.x,y_center=a.y; 
} 
void display() 
{ 
cout<<"I am a figure. The center is: "<<"("<<x_center<<","<<y_center<<")"; 
} 
}; 
class circle:public figure //类figure的子类circle 
{ 
private: 
double r; 
public: 
circle(point p,double rr) 
{ 
x_center=p.x,y_center=p.y,r=rr; 
} 
void move(point p) 
{ 
x_center=p.x,y_center=p.y; 
}
void display() 
{ 
cout<<"I am a circle, the center is: ("<<x_center<<","<<y_center<<"), the radius is:"<<r<<"."; 
} 
}; 
class rectangle:public figure //类figure的子类rectangle 
{ 
private: 
double widthval,lengthval; 
public: 
rectangle(point p,double lengthVal,double widthVal) 
{ 
x_center=p.x,y_center=p.y,widthval=widthVal,lengthval=lengthVal; 
} 
void display() 
{ 
cout<<"I am a rectangle, the center is: ("<<x_center<<","<<y_center<<"), the length is: "<<lengthval<<", the width is: "<<widthval<<"."; 
}
};
int main()
{
 double x,y,radius,width,length;
 cin>>x>>y;
 point p(x,y);
 p.display();
 cout<<'\n';
 cin>>radius;
 circle cir1(p,radius);
 cir1.display();
 cout<<'\n';
 cin>>length>>width;
 rectangle rectangle1(p,length,width);
 rectangle1.display();
 cout<<'\n';
 return 0;
}

23.集合类的实现

Description
定义一个集合类,集合的大小是不确定的,需要使用指针数据成员, 重载运算符“+”,“*”,“-”实现集合的并、交、差运算,对赋值运算符进行重载,定义拷贝构造函数,重载流运算符实现集合的输入、输出。注意,假设A={1,3,5},B={1,5,9},两个集合的差运算A-B,是指从集合A中减去集合B的元素,上面集合A-B的结果是{3}

类的定义如下:

class settype
{
public:
settype(); //构造函数,默认空集,n=0, set=NULL;
settype( const settype& B); //拷贝构造函数
~settype(); //析构函数

void getdata(int *a, int& num) const; //读值函数
void setdata(int *a, int num); //设值函数
int get_n() const; // 获取集合当前元素数目

settype operator+(settype B); //重载运算符+,实现集合并运算
settype operator*(settype B); //重载运算符*,实现集合交运算
settype operator-(settype B); //重载运算符-,实现集合差运算
settype operator=(settype B); //重载运算符=

private:
int *set; //数组指针
int n; //元素的个数
};

Input
输入有4行, 第1行输入集合A 的元素个数,第2行输入A 的元素值(数据之间用空格分开),第3行输入集合 B的元素个数,第4行输入B 的元素值,注意集合A,B的元素个数不能超过10

Output
输出有5行,分别输出集合A,集合B,A+B的结果, A*B的结果, A-B的结果,具体输出格式见Sample Output

Samples
Input 复制
5
1 3 5 7 9
3
1 4 6
Output
A={1,3,5,7,9}
B={1,4,6}
A+B={1,3,5,7,9,4,6}
A*B={1}
A-B={3,5,7,9}

#include  
using namespace std; 
typedef long long ll;
const int maxn=1e5+9;

class settype //定义类 
{ 

public: 
settype():n(0),set(NULL){}; 
settype(const settype& B) 
{ 
n = B.n; 
set = new int[n]; 
for (int i = 0; i < n; i++) 
set[i] = B.set[i]; } 
~settype() //析构函数 
{ 
delete[] set; 
} 
void setdata(int* a, int num) 
{ 
n = num; 
delete[]set;//释放内存 
set = new int[n]; 
for (int i = 0; i < n; i++) 
set[i] = a[i]; } 
void getdata(int* a) const 
{ 
for (int i = 0; i < n; i++) 
a[i] = set[i]; 
} 
int get_n() const 
{ return n; 
} 
bool exist(int x) const 
{ 
for (int i = 0; i < n; i++) 
{ 
if (set[i] == x) return true; 
} 
return false; } 
settype operator+(const settype& B) const 
{ 
settype temp; 
int* p_arr; 
int count = 0;//用于记录下标 
p_arr = new int[n + B.n]; 
for (int i = 0; i < n; i++) 
p_arr[count++] = set[i]; 
for (int i = 0; i < B.n; i++) 
if (!exist(B.set[i])) p_arr[count++] = B.set[i]; 
temp.setdata(p_arr, count); 
delete[] p_arr; 
return temp; } 
settype operator*(const settype& B) const 
{ 
settype temp; int* p_arr; 
p_arr = new int[n]; 
int count = 0; 
for (int i = 0; i < n; i++) 
if (exist(B.set[i])) p_arr[count++] = set[i]; 
temp.setdata(p_arr, count); 
delete[]p_arr; 
return temp; 
} 
settype operator-(const settype& B) const 
{ 
settype temp; 
int* p_arr; 
p_arr = new int[n]; 
int count = 0; 
for (int i = 0; i < n; i++) 
if (!exist(B.set[i])) p_arr[count++] = set[i]; 
temp.setdata(p_arr, count); 
delete[]p_arr; 
return temp; 
} 
settype operator=(const settype& B) 
{ 
if (this != &B)//不能是原来的 
{ 
n = B.n; 
delete[]set; 
set = new int[n]; 
for (int i = 0; i < n; i++) 
set[i] = B.set[i]; 
} 
return *this; } 
private: 
int* set; //数组指针 
int n; //元素的个数 
}; 
istream& operator>>(istream& is, settype& obj) 
{ 
int num, * p_arr; 
is >> num; 
p_arr = new int[num]; 
for (int i = 0; i < num; i++) 
is >> p_arr[i]; 
obj.setdata(p_arr, num); 
delete[] p_arr; 
return is; 
} 
ostream& operator<<(ostream& os, const settype& obj) 
{ 
int num, * p_arr; 
num = obj.get_n(); 
if (num == 0) os << "{}" << endl; 
else 
{ 
p_arr = new int[num]; 
obj.getdata(p_arr); 
os << "{"; 
for (int i = 0; i < num - 1; i++) 
os << p_arr[i] << ","; 
os << p_arr[num - 1] << "}" << endl; 
delete[] p_arr; 
} 
return os; 
} 
int main()
{
   settype A, B, C;    
   cin>>A>>B;

   cout<<"A="<<A;
   cout<<"B="<<B;

   C=A+B;
   cout<<"A+B="<<C;

    C=A*B;
   cout<<"A*B="<<C;

   C=A-B;
   cout<<"A-B="<<C;
   return 0;
}

24复数类(重载加减运算符)

Description
定义类表示复数,成员包括实部real和虚部imaginary,均为double类型
成员函数包括:无参的构造函数(实部和虚部分别赋值为1.0), 带两个参数的构造函数,重载“+”和“-”运算符 , display函数(输出格式形如"2.00+3.00i"),输出时要求 实部和虚部分别精确到两位小数

Input
分别输入两个复数的实部和虚部,一行输入一个复数,实部和虚部用空格分开,具体格式见Sample Input

Output
输出有2行,分别输出两个复数"+“和”-"的结果,具体格式见Sample Output

Samples
Input 复制
2 3
4 5
Output
6.00+8.00i
-2.00-2.00i

#include 
using namespace std; 

typedef long long ll;
const int maxn=1e5+9;

class Class 
{ 
private: //私有成员 
double real,image;

 
public: 
Class() { //默认构造函数 
real=1.,image=1.; }; 
Class(double a,double b) //带参构造函数 
{ 
real=a,image=b; } 
void display() //输出函数 
{ 
printf("%.2lf",real); 
if(image>0) cout<<"+"; 
printf("%.2lfi\n",image); 
} 

Class operator+(const Class& a) //重载运算符 
{ 
Class ans; 
ans.real=this->real+a.real; 
ans.image=this->image+a.image; 
return ans; 
} 

Class operator-(const Class& a) //重载运算符 
{ 
Class ans; 
ans.real=this->real-a.real; 
ans.image=this->image-a.image; 
return ans; 
}
};
int main() 
{

double x,y,x1,y1; 
cin>>x>>y>>x1>>y1; 
Class a(x,y),b(x1,y1); 
(a+b).display(); 
(a-b).display(); 
return 0; 
}

25.学生类数组

Description
(1)输入班级人数,使用new动态创建学生信息数组存储学生信息。学生信息使用student类存放,包括姓名(不包含空格),年龄。

(2)编写student类的默认构造函数,默认姓名为空字符串,年龄为0

(3)编写student类的输入函数input,能够输入每个学生的姓名,年龄

(4)编写student类的输出函数display,能够输出每个学生的姓名,年龄

(5)编写排序函数sort,能够按照年龄从小到大对学生进行排序

主函数输入班级人数,创建数组,输入学生信息,对学生年龄进行排序,然后输入排序后的信息

Input
输入信息有多个,第一行N表示班级人数,其余每一行为学生的信息(姓名,年龄,中间空格隔开)

Output
排序后的学生信息

Samples
Input 复制
3
Mary 22
Lucy 12
Mike 19
Output
Lucy 12
Mike 19
Mary 22

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;


class student {//创建类student
 
	public:
		string name;
		int age;
		student() {
			name=' ';
			age=0;
		}
		void input();
		void display();
};
void student::input(){
	cin>>name>>age;
}
void student::display(){
cout<<name<<" "<<age<<endl;
}
		

void sort(int n,student *stu) {//对函数体进行排序 
	student a;
	for(int i=0; i<n; i++) {//运用冒泡排序 
		for(int j=0; j<n-i-1; j++) {
			if(stu[j].age>stu[j+1].age) {
				a.age=stu[j].age,stu[j].age=stu[j+1].age,stu[j+1].age=a.age;
				a.name=stu[j].name,stu[j].name=stu[j+1].name,stu[j+1].name=a.name;
			}
		}
	}
}
int main() {
	int n,i;
	cin>>n;
	student *stu;
	stu=new student[n];//用new创建新的数组 
	for(i=0; i<n; i++) {
		stu[i].input();//利用数组进行输入 
	}
	sort(n,stu);
	for(i=0; i<n; i++) {//利用数组输出 
		stu[i].display();
	}
	return 0;
}

26. reverse_arr

Description
编写函数模板reverse_arr,将数组元素逆置。数组元素可以为任意数据类型。

Input
输入数据为一行,第一个为正整数n(n<=10),表示数组元素的数目,其余为数组元素

Output
逆置后的数组

Samples
Input 复制
4 5 10 15 7
3 2.3 4.7 3.5
2 english chinese
Output
7 15 10 5
3.5 4.7 2.3
chinese english

#include 
using namespace std; 
typedef long long ll;
const int maxn=1e5+9;

template <typename T> //函数模板定义数组类 
void reverse_arr(T a[],int n) //数组名为a,数组长度为n 
{ 
T b[n+1]; //定义一个数组b 
for(int i=0;i<n;i++) b[i]=a[i]; //将数组 a的值赋给b 
for(int i=0,j=n-1;i<n;j--,i++) a[i]=b[j]; 
} 

int main() 
{ 
int i_arr[10]; //定义三个类型的数组 
float f_arr[10]; 
string s_arr[10]; 
int n; 
cin >> n; 
for(int i=0;i<n;i++) cin>>i_arr[i]; 
reverse_arr(i_arr,n); 
cout<<i_arr[0]; 
for(int i=1;i<n;i++) cout<<" "<<i_arr[i]; 
cout<<'\n'; 
cin >> n; 
for(int i=0;i<n;i++) cin>>f_arr[i]; 
reverse_arr(f_arr,n); 
cout<<f_arr[0]; 
for(int i=1;i<n;i++) cout<<" "<<f_arr[i]; 
cout<<'\n'; 
cin >> n; 
for(int i=0;i<n;i++) cin>>s_arr[i]; 
reverse_arr(s_arr,n); 
cout<<s_arr[0]; 
for(int i=1;i<n;i++) cout<<" "<<s_arr[i]; 
return 0; 
}


27. 电梯类

Description
设有一栋十层的建筑物,创建一个电梯类,实现以下功能

(a) 电梯从第1层启动

(b) 按+时电梯上升一层,当电梯在10层时忽略此命令

© 按-时电梯下降一层,当电梯在1层时忽略此命令

(d) 按S时电梯将返回到第1层,并停止。

(e) 电梯从一层升/降到另一层,显示楼层数字

编写主函数生成一个电梯对象,从键盘输入字符运行电梯,输入字符S结束。

Input
输入字符’+’,’-’,‘S’,每个字符占一行。注意:输入字符个数为任意多个,遇到S,输入结束。

Output
输出电梯运行层数。

Samples Input 复制 + + + - S

Output
current floor:2
current floor:3
current floor:4
current floor:3
current floor:2
current floor:1

#include 
using namespace std; 
typedef long long ll; 

const int maxn=1e5+9;
class Clock //定义类 
{ 
private: //私有成员 
char oper; 
int ans=0; 

public: 
Clock() //默认构造函数 
{ 
ans=1; 
} 
void input(char f) //输入函数 
{ 
oper=f; 
} 
void fun() //操作函数 
{ 
if(oper=='+') //执行+时 
{ if(ans!=10) ans++,cout<<"current floor:"<<ans<<endl; 
} 
else if(oper=='-') //执行-时 
{ 
if(ans!=1) 
{ ans--; 
cout<<"current floor:"<<ans<<endl; 
} } 
else if(oper=='S') 
{ 
while(ans--&&ans) 
{ 
cout<<"current floor:"<<ans<<endl; 
} 
} 
} }; 
int main()
{
	char ch;
	Clock a;
	while(1){
		cin>>ch;
		a.input(ch);
		a.fun();
		if(ch=='S') return 0;
	}
	return 0;
 }

28 日期类

Description
定义日期类Date,数据成员包含:year,month,day,成员函数包括:

(1) 构造函数Date (int year, int month, int day ),可以设定默认的形参值为2008年1月1日

(2) 赋值函数,assign(int year, int month, int day) 用来给三个数据成员赋值,暂时不考虑非法赋值的情况.

(3) 显示日期函数,display( ),按规定格式“年-月-日”输出,例如2000年5月1日,输出 2000-5-1

(4) 判断闰年函数,bool Leap_year ( ),返回值为布尔型,是闰年返回true,否则返回false

(5) 计算当前日期后1天的日期的函数,void increment(),计算时必须注意闰年、跨月、跨年的情况

例如:若当前日期为2016-12-31,执行increment();则日期为2017-1-1

若当前日期为2017-2-28,执行increment();则日期为2017-3-1

若当前日期为2017-1-31,执行increment();则日期为2017-2-1

(6) 计算当前日期后n天的日期的函数,void increment(int n),计算时必须注意闰年、跨月、跨年的情况

例如:若当前日期为2016-8-10,执行increment(5);则日期为2016-8-15

若当前日期为2016-2-27,执行increment(3);则日期为2016-3-1

若当前日期为2016-12-30,执行increment(5)则日期为2017-1-4

(提示:可先完成增加1天的函数,然后循环执行该函数即可。)

主函数如下所示,先输出date1和date2的日期,然后按“日 月 年”的格式输入一个日期,用assign函数给date3赋值,并输出date3,再输入一个天数,即输入n(1<=n<=30),对象date3调用increment函数,最后输出计算后的新日期

int main()

{

Date date1, date2(2016,5,1),date3;

int n,day,month,year;

date1.display();

date2.display();

cin>>year>>month>>day;

date3.assign(year,month,day);

date3.display();

cin>>n;

date3.increment(n);

date3.display();

return 0;

}

Input
输入年,月,日,增加天数n,输入用空格隔开。

Output
输出main函数执行结果

Samples
Input 复制
2017 12 31 70
Output
2008-1-1
2016-5-1
2017-12-31
2018-3-11

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
class Date{//定义日期类 
	
	private://私有成员 
		int year;
		int month;
		int day;
		
	public://共有成员 
		Date(int a=2008,int b=1,int c=1)//构造函数 
		{
		   year=a;month=b;day=c;
		}
		
		void assign(int a,int b,int c)//赋值函数 
		{
			year=a;month=b;day=c;
		}
	
	
	    void display(){//输出函数 
	       cout<<year<<"-"<<month<<'-'<<day<<'\n';
		}
		
		bool Leap_year(){//判断闰年函数 
		  if(year%100!=0&&year%4==0||year%400==0)
		  return 1;
		  return 0;
		}
		
		void increment(int n)//计算日期后的函数 
		{
		   while(n--)
		   {
		    bool flag;
		    flag=Leap_year();
		    int x=0;
		    if(flag&&month==2)
		    x=29;
		    else if(month==2)
		    x=28;
		    else if(month==4||month==6||month==9||month==11)
		    x=30;
		    else
		    x=31;
		    day++;
		    if(day==x+1){
		    	day=1;
		    	month++; 
			}
		    if(month==13)
		    {
		    	month=1;
		    	year++;
			}
		   }
		}

};
int  main()
{
	Date date1, date2(2016,5,1),date3;

int n,day,month,year;

date1.display();

date2.display();

cin>>year>>month>>day;

date3.assign(year,month,day);

date3.display();

cin>>n;

date3.increment(n);

date3.display();
	
	
	
    return 0;
}

29 日期类加强版

Description
定义日期类Date,数据成员包含:day,month,year,成员函数包括:

(1) 构造函数 Date (int day, int month, int year ),可以设定默认的形参值为2008年1月1日

(2) 赋值函数,void assign(int day, int month, int year) 用来给三个数据成员赋值,需要对日,月的数据进行判断,如果日期数据大于当月的天数,月份数据大于12,则可以用取余运算使数据在合法的取值区间内。

例如:

若输入32 3 2018,期中32是非法数据,32%31=1,所以最后得到的合法日期应该是1/3/2018

若输入15 20 2018,期中20是非法数据,20%12=8,所以最后得到的合法日期应该是15/8/2018

如果算出来余数为0,则月份赋值为12,日期则为对应月份的最大天数,注意区分大小月和2月(注意闰月情况)

(3) 显示日期函数,void display( ),按规定格式“日/月/年”输出,例如:2000年5月1日,输出 1/5/2000

(4) 判断闰年函数,bool Leap_year ( ),返回值为布尔型,是闰年返回true,否则返回false

(5) 计算当前日期后n天的日期的函数,void increment(int n),计算时必须注意闰年、跨月、跨年的情况,假设测试数据中的n的范围为1<=n<=30

例如:

若当前日期为10/8/2016,执行increment(5);则日期为15/8/2016

若当前日期为27/2/2016,执行increment(3);则日期为1/3/2016

若当前日期为30/12/2016,执行increment(5);则日期为4/1/2017

主函数如下所示,先输出date1和date2的日期,然后按“日 月 年”的格式输入一个日期,用assign函数给date3赋值,并输出date3,再输入一个天数,即输入n(1<=n<=30),对象date3调用increment函数,最后输出计算后的新日期

int main()

{ Date date1, date2(1,5,2016),date3;

int n,day,month,year;

 cin>>day>>month>>year;

date3.assign(day,month,year);

cin>>n;

date1.display();

date2.display();

date3.display();

date3.increment(n);

date3.display();

return 0; 

}

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
class Date{
   private://私有成员 
   	int year;
   	int month;
   	int day;
   	
   public:
   	
   	Date(int a=1, int b=1,int c=2008)//构造函数 
   	{
   	  day=a;
   	  month=b;
   	  year=c;
	}
	
	bool Leap_year(){//判断闰年函数 
	   if(year%100!=0&&year%4==0||year%400==0)
	   return 1;
	   return 0; 
	 }
	 
	void assign(int a,int b,int c)//赋值函数 
	{
	   year=c;
	   int x;
	   bool flag=Leap_year();
	   month=b%12;
	   if(month==0)
       month=12;
       if(month==2&&flag==1)
       x=29;
       else if(month==2)
       x=28;
       else if(month==4||month==6||month==9||month==11)
       x=30;
       else
       x=31;
       day=a%x;
       if(day==0)
       day=x;
	}
	
	
	void display()//输出函数 
	{
	  cout<<day<<'/'<<month<<'/'<<year<<'\n';
	}
	
	void increment(int n)// 日期函数 
	{
	  while(n--)
	  {
	    bool flag;
	    flag=Leap_year();
	    int x=0;
	    if(month==2&&flag==1)
	    x=29;
	    else if(month==2)
	    x=28;
	    else if(month==4||month==6||month==9||month==11)
	    x=30;
	    else
	    x=31;
	    day++;
	    if(day==x+1)
		{
			day=1;
			month++;
		 }
		 if(month==13)
		 {
		   month=1;
		   year++;
		  } 
	  }
	}
	 
	 
	
};
int main()
{
	 Date date1, date2(1,5,2016),date3;

    int n,day,month,year;

     cin>>day>>month>>year;

    date3.assign(day,month,year);

    cin>>n;

    date1.display();

    date2.display();

    date3.display();

    date3.increment(n);

    date3.display();
	
	
	
   return 0;
 } 

30 机器人类

Description

机器人类的构造函数及成员变量为:

class robot
{
public:
robot(float x = 0, float y = 0) : x_coord( x ), y_coord(y)
{}
void display_position()
{
cout << “(” << x_coord << “,” << y_coord << “)” << endl ;
}
private:
float x_coord, y_coord ;
} ;

补充其中的成员方法,使之能运行以下的main函数

int main()
{
float x, y;
cin >> x >> y;
robot r2d2(x, y); // Constructor sets the initial position.
r2d2.left(1.3); // Move robot left 1.3 cms.
r2d2.display_position();
r2d2.back(4.21); // Move robot back 4.21 cms.
r2d2.display_position();
r2d2.right(3.1); // Move robot right 3.1 cms.
r2d2.display_position();
r2d2.return_to_base(); // Sets the position to (0,0).
r2d2.forward(0.3); // Move robot forward 3.1 cms.
r2d2.display_position();
r2d2.goto1(x, y);
r2d2.display_position();
return 0;
}

Input
输入机器人的初始坐标

Output
输出结果

Samples
Input 复制
12 22
Output
(10.7,22)
(10.7,17.79)
(13.8,17.79)
(0,0.3)
(12,22)

#include
using namespace  std;
typedef long long ll;
const int maxn=1e5+9;

class robot//定义机器类 
{
	
public:
robot(float x = 0, float y = 0) : x_coord( x ), y_coord(y)
{}

void display_position()
{
cout << "(" << x_coord << "," << y_coord << ")" << endl ;
}

bool left(double x)
{
   if(x_coord-x>=0)
   {
     x_coord=x_coord-x;
     return 1;
   }
   return 0;
}

bool right(double x)
{
   if(x_coord+x<=100)
   {
      x_coord=x_coord+x;
      return 1;
   }
   return 0;
}

bool forward(double y)
{
   if(y_coord+y<=100)
   {
   	y_coord=y_coord+y;
   	return 1;
   }
   return 0;
}

bool back(double y)
{
   if(y_coord-y>=0)
   {
    y_coord=y_coord-y;
    return 1;
	} 
	return 0;
}

bool goto_position(double x,double y){
   if(x>100||y>100)
   {
     return 0;
     x_coord=x;
     y_coord=y;
     return 1;
   }
}

bool return_to_base()
{
   x_coord=0;
   y_coord=0;
}

bool goto1(double x,double y){
	   x_coord=x;
	   y_coord=y;
}
private:
float x_coord, y_coord ;
};


int main()
{
  float x, y;
 cin >> x >> y;
 robot r2d2(x, y); // Constructor sets the initial position.
 r2d2.left(1.3); // Move robot left 1.3 cms.
 r2d2.display_position();
 r2d2.back(4.21); // Move robot back 4.21 cms.
 r2d2.display_position();
 r2d2.right(3.1); // Move robot right 3.1 cms.
 r2d2.display_position();
 r2d2.return_to_base(); // Sets the position to (0,0).
 r2d2.forward(0.3); // Move robot forward 3.1 cms.
 r2d2.display_position();
 r2d2.goto1(x, y);
 r2d2.display_position();	
	
  return 0;	
}

31 机器人类

Description
假设有一个机器人,它可以在一个有限的区域内前,后,左,右的移动,该区域为正方形,4个顶点的坐标为:(0,0),(0,100),(100,100),(100,0),机器人可以通过调用不同的函数来实现移动,但是在机器人移动的过程中,如果要移动到的位置坐标超出这个范围,则不能进行移动,此时需要输出错误提示信息“position error! ”,如果机器人可以移动,则移动成功后应输出机器人新的位置坐标。机器人类的部分定义如下:

class robot

{

public:

robot(double x = 0, double y = 0) : x_coord( x ), y_coord(y)  { }

void display_position()  // Inspector function to display the robot's position

      {  cout << "(" << x_coord << "," << y_coord << ")" << endl ;    }

...需要补充的其它成员函数 ...

private:

double x_coord, y_coord ; // 看main函数确定这两个数据成员代表的含义
} ;

补充其它的成员函数有6个:left(), right(), forward(), back(), goto_position(), void return_to_base(),使之能运行以下的main函数,函数的参数如何定义,请根据main函数中的函数调用来确定(请仔细阅读main函数),前5个函数 left(), right(), forward(), back(), goto_position()返回值类型为bool型,如果要移动的位置超出范围,则返回false,如果移动移动成功,则返回true,

int main()

{ double px, py;

robot puppy( 59.6, 28.1 ) ; // Constructor sets the initial position.

if( puppy.left( 1.3 ) )

    puppy.display_position() ;       // Move robot left 1.3 cms, New position is ( 58.3,28.1)

else cout<<“position error!\n”;

if(puppy.back(12.0)) 

     puppy.display_position() ;        // Move robot back 12.0 cms, New position is ( 58.3,16.1)

else cout<<“position error!\n”;

if(puppy.right( 60.0 ) ) 

    puppy.display_position() ;     // Move robot right 60.0 cms, 58.3+60=118.3>100, output "position error!"

else cout<<“position error!\n”;

puppy.return_to_base() ;       // Sets the position to (0,0)

puppy.display_position() ;

puppy.forward( 3.5 );             // Move robot forward 3.5 cms,  New position is ( 0, 3.5 )

puppy.display_position();

cin>>px>>py;

if(puppy.goto_position( px, py ))

        puppy.display_position();

else       cout<<"position error!\n";  

return 0;

}

Input
只有一行输入数据,依次输入px, py 的值,两个实数用空格分开

Output
输出有6行,每行输出一个位置,若位置错误则输出信息“position error!”具体格式见Sample Output

Samples
Input 复制
18.5 65.3
Output
(58.3,28.1)
(58.3,16.1)
position error!
(0,0)
(0,3.5)
(18.5,65.3)

#include
using namespace std;
typedef long long ll;
const int maxn=1e5+9;

class robot//定义类 
{
	
	
public:
    robot(double x = 0, double y = 0) : x_coord( x ), y_coord(y)  { }//构造函数 

     void display_position()
	 {
	   cout<<"("<<x_coord<<","<<y_coord<<")"<<'\n';
		  }     
          
    bool left(double x)
    {
    	if(x_coord-x>=0)
    	{
    	   x_coord=x_coord-x;
    	   return 1;
		}
		return 0;
	}
	
	bool right(double x)
    {
        if(x_coord+x<=100)
        {
           x_coord=x_coord+x;
           return 1;
		}
		return 0;
	}
	
	bool forward(double y)
{
   if(y_coord+y<=100)
   {
     y_coord=y_coord-y;
     return 1;
   }
   return 0;
  }
  
bool back(double y)
{
   if(y_coord-y>=0)
   {
     y_coord=y_coord-y;
     return 1;
   }
   return 0;
}

bool goto_position(double x,double y)
{
	if(x>100||y>100)
	return 0;
	x_coord=x;
	y_coord=y;
	return 1;	
   } 
   
 void return_to_base()
 {
   x_coord=0;
   y_coord=0;
 }
 
 private:
 	double x_coord,y_coord;
} ;
int main()
{
	double  px, py;

robot puppy( 59.6, 28.1 ) ;      // Constructor sets the initial position.

if( puppy.left( 1.3 ) ) 

        puppy.display_position() ;       // Move robot left 1.3 cms, New position is ( 58.3,28.1)

else        cout<<"position error!\n";    

    if(puppy.back(12.0)) 

         puppy.display_position() ;        // Move robot back 12.0 cms, New position is ( 58.3,16.1)

else       cout<<"position error!\n"; 

    if(puppy.right( 60.0 ) ) 

        puppy.display_position() ;     // Move robot right 60.0 cms, 58.3+60=118.3>100, output "position error!"

  else      cout<<"position error!\n"; 
    puppy.return_to_base() ;       // Sets the position to (0,0)
    puppy.display_position() ;
    puppy.forward( 3.5 );             // Move robot forward 3.5 cms,  New position is ( 0, 3.5 )
    puppy.display_position();
    cin>>px>>py;
    if(puppy.goto_position( px, py ))
            puppy.display_position();
    else       cout<<"position error!\n";  
	return 0;
}

你可能感兴趣的:(c++)