C++课后习题汇总

写在前面

今天是我发CSDN的第一天,希望自己能将今后能利用CSDN这个平台记录自己学习成长中的一些点滴。
我将大一学习C++时完成课后作业的一些代码整理了一些放到平台上来以供大家参考和以后自己复习。里面可能有一些小错误还望指正。

习题加代码如下

P212/8.1

下面是一个类的测试程序,试设计出能使用如下测试程序的类:

#include<iostream>
using namespace std;
class test
{
public:
	void initx(int x, int y) {
		this->x = x; this->y = y;
	}
	void print()
	{
		cout << x << "*" << y << x*y << endl;
	}
private:
	int x, y;
};
#include<iostream>
#include"1.h"
int main()
{
	test x;
	x.initx(30, 20);
	x.print();
	return 0;

}

P212/8.4

定义并实现一个矩形类Crectangle。

#include<iostream>
using namespace std;
class Crectangle 
{
public: Crectangle(int le = 0, int w = 0, int t = 0, int l = 0) :top(t), left(l) {
	if (le < 0 || w < 0)
		cout << "输入有误";
	else length = le, width = w;
}
		void settop(int t) { top = t; }
		void setleft(int l) { left = l; }
		void setLength(int l) { length = l; }
		void setwidth(int w) { width = w; }
		int perimeter() { return 2 * (length + width); }
		int Area() { return length*width; }
		int Getwidth() { return width; }
		int Getlength() { return length; }
		bool IsSquare() { return length == width ? true : false; }
			void  move(int t, int l) { top += t, left += l; }
		void Size(int l, int w) { Crectangle(l, w); }
		void Where(int&x,int&y);//****引用以返回多个类型
		void PrinteRectangle();
private: int top, left, length, width;

};
void Crectangle::Where(int&x, int&y)
{
	x = top;
	y = left;
}
void Crectangle:: PrinteRectangle()
{
	cout << "四个位置点\n(" << top << ","<<left << ")" << endl;

	cout << "(" << top+length <<","<< left << ")" << endl;
	cout << "(" << top  << ","<<left-width<< ")" << endl;
	cout << "(" << top + length <<","<< left-width<< ")" << endl;

}


#include<iostream>
#include"Cre.h"
using namespace std;
int main()
{
	Crectangle a(21, 21, 21, 21);
	cout << "面积为" << a.Area() << "长度为\t" << a.Getlength() << "宽为\t" << a.Getwidth() << "周长为" << a.Getlength() << endl;
	if (a.IsSquare())cout << "是正方形";
	else cout << "不是正方形";
	a.PrinteRectangle();

	cout << "移动,输入移动单位" << endl;
	cout << "向右移动:" << endl;
	int x, w;
	cin >> x;
	cout << "向上移动:" << endl;
	cin >> w;
	a.move(x, w);
	a.PrinteRectangle();
	cout << "改变边长\t" << "长改变为:" << endl;
		cin >> x;
		cout << "宽改变为:" << endl;
		cin >> w;
		a.setLength(x);
		a.setwidth(w);
		if (a.IsSquare())cout << "是正方形";
		else cout << "不是正方形";
	//	if (a.IsSquare())cout << "是正方形";
	
		cout << "面积为" << a.Area() << "长度为/t" << a.Getlength() << "宽为/t" << a.Getwidth() << "周长为" << a.Getlength() << endl;
		a.Where(x, w);
		cout << "矩形的位置点为" << "("<<x<<","<<w<<")\n";
		return 0;
}






P213/8.6

在某次歌手大赛中,有JudgeNum个评委给选手打分,参加比赛的选手有PlayerNum名,现为比赛记分编写一个CompetitionResult类。
(1)写出所有成员函数的实现代码。
(2)编写main()函数对该类进行测试。在函数体中,定义一个CompetitionResult类的对象数组r[PlayerNum],它的每个元素记录着每个选手的所有信息,各评委的打分通过键盘输入,在屏幕上应有提示信息进行交互式操作,比赛结果按选手得分从高到低排序输出。

#include<iostream>
#include"CO.h"
#define Playernum 20
using namespace std;
int main()
{
	CompetionResult*q=new CompetionResult [Playernum];
	cout << "请分别输入player 姓名:/t 号码 /t";
	for (short i = 0; i < Playernum; i++)
	{
		short n;
		char*p;
		cin >> p >> n;
		q[i].Setname(n, p);//? 为什么要用  .  而不用-》
	}
	cout << "请各位评委输入分数" << endl;
	for(int j=0;j<Playernum;j++)
		for (int i = 0; i < Judgenumber; i++)
		{
			float s;
			cin >> s;
			q[j].SetScore(i, s);
		}
	cout << "最终结果为:" << endl;
	show(q, Playernum);

	return 0;
}

#include<iostream>
using namespace std;
#define Judgenumber 10
class CompetionResult
{
	short num;
	char name[10];
	float score[Judgenumber];
	float average;
public:
	CompetionResult() { num = 0; name[0] = '\0' ; score[Judgenumber] = { 0 }; average = 0; }
  CompetionResult(short n, char*p);
  void Setname(short n, char*p) {
	  num = n;
	  if(strlen(p)<10)
	  strcpy(name, p);
	  else cout << "出错" << endl;
}
  float Maxscore();
  float minscore();
  void SetAvg();
  float GetAvg() { return average; }
  short Getnum() { return num; }
  void Setnum(short n) { num = n; }
  char* Getname() { return name; }
  float GetScore(int j) { return score[j]; }
  void SetScore(int j, float s) { score[j] = s; }
  
  friend void show(CompetionResult*q, int n);


};
CompetionResult::CompetionResult(short n, char*p)
{
	num = n;
	strcpy(name, p);
}
float  CompetionResult::Maxscore()
{
	float m=score[0];
	
	for (int i = 1; i < Judgenumber - 1; i++)
		if (m < score[i])
			m = score[i];
	return m;
}
float CompetionResult::minscore()
{
	float m = score[0];

	for (int i = 1; i < Judgenumber - 1; i++)
		if (m >score[i])
			m = score[i];
	return m;

}
void CompetionResult::SetAvg()
{
	float s = 0;
	for (int i = 0; i < Judgenumber - 1; i++)
		s += score[i];
	average = (s - Maxscore() - minscore()) / 8;

}

void show(CompetionResult*q, int n)//不能单纯的排序!!!
{
	/*float s[n];
	for (int i = 0; i < n; i++)
		s[i] = (q + i)->average;
	float m;
	int i = 1;
	for ( ; i < n - 1; i++)
		m = s[i - 1];
	for (int j = i; j < n; j++)
		if (m > s[j])m = s[j];
	s[i - 1] = m;
	for (i = 0; i < n; i++)
		cout << s[i] << "/t";*/
	//方法2
	/*int s[Judgenumber] = { 0 };//并不是常量表达式?/?
	float a[Judgenumber];
	short b[Judgenumber];
	float m;
	int i = 1;
	for (; i < n - 1; i++)
		m = (q + i)->average;
	for (int j = i; j < n; j++)
		if (m > (q + j)->average)s[i]++;
	a[s[i]] = (q + i)->average;
	b[s[i]] = (q + i)->num;
	for (i = 0; i < n; i++)
		cout << "选手/t"<<b[i]<<"平均分为/t"<<a[i] << "名次为/t"<<i<<endl;//仍无法对应选手名再定义一个数组*/

	//最优解,对象整体赋值,直接排序法的本质
	CompetionResult temp;
	
	int  m;
	int i = 1;
	for (; i < n - 1; i++)
		m = i-1;
	for (int j = i; j < n; j++)
		if (q[m].average < q[j].average)m = j;
	temp = q[m];
	q[m] = q[i - 1];
	q[i - 1] = temp;
	for (i = 0; i < n; i++)
		cout << q[i].Getname() << "/t"<<q[i].average<<"/t第"<<i+1<<"名"<<endl; 
}




P235/9.2

声明一个图形基类Shape,在它的基础上派生出矩形类Rectangle和圆形类Circle,它们都有计算面积和周长,输出图形信息等成员函数,再在Rectangle类的基础上派生出正方形类Square。编写程序完成各类的定义和实现,以及类的使用。

#include<iostream>
#include"class.h"
using namespace std;
int main()
{
	double l, w;
	cout << "请输入矩形的长和宽:" << endl;
	cin >> l >> w;

	Rectangle RE(l,w);
	cout << "请输入正方形的边长:" << endl;
	cin >> w;
	Square S(w);
	cout << "请输入圆的半径:" << endl;
	cin >> w;
	Circle C(w);
	shape* p = &RE;
	cout << "周长为:/t" << p->zhouchang() << "面积为:/t" << p->Area() << endl;
	p->print();
	p = &S;
	cout << "周长为:/t" << p->zhouchang() << "面积为:/t" << p->Area() << endl;
	p->print();

	p = &C;
	cout << "周长为:/t" << p->zhouchang() << "面积为:/t" << p->Area() << endl;
	p->print();

	return 0;
}
#ifndef CLASS_H
#define CLASS_H
#include<iostream>
#include<math.h>
#define PI 3.14
using namespace std;

class shape
{
public:
	virtual double zhouchang() = 0;
	virtual double Area() = 0;
	virtual void  print() = 0;

};
class Rectangle:public shape
{
public:
	Rectangle(double l, double w) :longth(l), width(w) {}
	double zhouchang() { return 2*(longth+width); }
	double Area() {
		return longth*width
			;
	}
	void  print();
protected: double longth, width;
};
void Rectangle::print()
{
	cout << "图形为矩形   /t 长为" << longth << "/t 宽为:" << width<<endl;
	
}
class Square: public Rectangle
{
public:	Square(double w) : Rectangle(w, w) {}
	void print() { cout << "图像为正方形 宽为/t" << longth << endl; }
};
class Circle:public shape
{
public:Circle(double r) :radios(r) {}
	double zhouchang() { return 2 * PI*radios; }
	double Area() { return PI*radios*radios; }
	void  print() { cout << "图形为圆 /t 半径为:/t" << radios << endl; }
private:double  radios;
};
#endif // !CLASS.H



P235/9.5

某销售公司有销售经理和销售员工,月工资的计算方法是:销售经理的底薪为4000元,并将销售额的2/1000作为提成,销售员工无底薪,只提取销售额的5/1000作为工资。编写程序:
(1)定义一个基类EmployEe,它包含3个数据成员number(职员编号),name(姓名)和salary(工资),以及用于输入编号和姓名的构造函数。
(2)由Employee类派生Salesman类。Salesman类包含两个新数据成员Commrate(提成比例)和sales(销售额),还包含用于输入销售额并计算销售员工工资的成员函数pay()和用于输出的成员函数print()。
(3)由Salesman类派生Salesmanager类。SaleSmanager类包含新数据成员monthlypay(底薪),以及用于输入销售额并计算销售经理工资的成员函数pay(),用于输出的成员函数main()。
(4)编写main函数中,测试所设计的类结构,并求若干个不同员工的工资。

int main()
{
	Saleman worker[3] = { Saleman(1,"郭靖", COMMRATEWORKER
	),Saleman(2,"黄蓉",COMMRATEWORKER),Saleman(3,"洪七公",COMMRATEWORKER) };
	Salesmanager manager[2] = { Salesmanager(4,"郑一",COMMRATEMANAGER,MONTH),Salesmanager(5,"黄家振",COMMRATEMANAGER,MONTH) };
	double sa;
	for (int i = 1; i <= 5; i++)
	{
		cout << "请输入编号为" << i << "的销售额\n";
		cin >> sa;
		if (i <= 3)
		{
			worker[i - 1].pay(sa);
		worker[i - 1].print();
		}
		else {
			manager[i - 4].pay(sa);
			manager[i - 4].print();
		}

	}

	system("pause"); return 0;

#ifndef 销售部_H
#define 销售部_H
#include<iostream>
using namespace std;
class Employee
{
public:Employee(int num, char *p) { number = num;
	   strcpy_s(name,30, p);//不安全??
}
	   void Setsalary(double sala) { salary = sala; }
	   double Getsalary() { return salary; }
protected:char name[30];
		int number;
		double salary;
};
class Saleman :public Employee
{
public:void pay(double sa) { Employee::Setsalary(commrate*(sales = sa)); }
	   Saleman(int num, char *p,double commra) :Employee( num, p),commrate(commra) {}//构造函数中不能用this指针??
	   void print() { cout<<"销售员工\t"<<name<<"工资为:"<< Employee::Getsalary()<<endl; }
protected://const static double commrate;
	double commrate, sales;
		
};
//const double Saleman::commmrate = 5.0 / 1000.0;
class Salesmanager :public Saleman
{
public:
	Salesmanager(int num, char *p,  double commrate, double mon) : Saleman( num,p ,  commrate), monthlypay(mon) {}
	void pay(double sa) {
		Saleman::Setsalary(commrate*(sales = sa) + monthlypay);
	}
	void print() { cout << "销售经理" << name << "工资为:" << Saleman::Getsalary() << endl; }
private:double monthlypay;
};

#endif // !销售部-H

P264/10.1

定义一个复数类Complex,重载运算符+,-,*,/,使之能用于复数的加减乘除运算。运算符重载函数作为Complex类的成员函数。编写程序,分别求两个复数之和差积商。

#include<iostream>
#include"Complex.h"
using namespace std;
int main()
{
	Complex a(1, 2), b(-10, 2), c(10, -2);
	cout << "原复数分别为:\n\t\t\t";
	a.print();
	b.print();
	c.print();
	Complex d = a + b - c;//不写=的重载是否可以??
	cout << "a+b-c=";
	d.print();
	//or (a+b-c).print();
	cout << "a*b=";
	(a*b).print();
	cout << "a/b=";
	(a / b).print();

	return 0;
}

//为复数重载+、-运算符,编程实现(6+7i)+(7+8i)和(6+7i)-(7+8i)的运算。
#ifndef Class2_h
#define Class2_h//为复数重载+、-运算符,编程实现(6+7i)+(7+8i)和(6+7i)-(7+8i)的运算。
#include <iostream>
using namespace std;
class Complex
{
public:Complex(double r = 0, double i = 0) { this->r = r, this->i; }
	   Complex(Complex& a) { r = a.getreal(); i = a.getim(); }
	   void setreal(double r) { this->r = r; }
	   void setim(double i) { this->i = i; }
	   double getreal() { return r; }
	   double getim() { return i; }
	   void print() { cout << "(" << r << "," << i << ")\t"; }
	   Complex operator +(Complex b);
	   friend Complex operator -(Complex &a, Complex &b);
	   Complex operator*(Complex &a);
	   Complex operator/(Complex &a);
private:double r, i;
};
Complex Complex::operator+(Complex b)
{
	return Complex(r + b.getreal(), i + b.getim());
}
Complex operator-(Complex &a, Complex &b)
{
	return Complex(a.r - b.r, a.i - b.i);
}
Complex Complex::operator*(Complex &a)
{
	return Complex(r*a.getreal() - i*a.getim(), i*a.getreal() + r*a.getim());
}
Complex Complex::operator/(Complex& a)//参数为类的对象应该用引用
{
	return Complex(r / a.getreal() + i / a.getim(), -(r / a.getim() + i / a.getreal()));//不考虑分母存在0的情况
}
#endif // !Class2_h





P264/10.2

定义一个日期类Date,包括年月日等私有数据成员。

#include<iostream>
#include"Cdate.h"
using namespace std;
int main()
{
	int y1, y2, m1, m2, d1, d2;
	cout << "请输入日期  年/月/日\n";
	cin >> y1>> m1 >> d1;
	cout << "请输入第二个日期  年/月/日\n";
	cin >> y2 >> m2 >> d2;
	Date a(y1, m1, d1), b(y2, m2, d2);
	a.print();
	b.print();
	int days;
	cout << "请输入添加天数\n";
	cin >> days;
	Date c =a+days;
	cout << "添加后为:";
	c.print();
	cout << "请输入减去天数:";
	cin >> days;
	c = a - days;
	cout << "减去后为:"<<endl;
	c.print();
	a.print();
	cout << "-";
	b.print();
	cout << "=";
	cout << a - b;
	system("pause");
	return 0;
}
#include<iostream>
using namespace std;
class Date
{
public:Date(int ye, int mo, int da) :y(ye), m(mo), d(da) {}
	   bool Isrun() { return ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) ? true : false; }
	   Date operator+(int days);//还需再优化,加上后不改变值
	   Date operator-(int days);
	   int operator-(Date &b);
	   int getyear() { return y; }
	   int getmonth() { return m; }
	   int getday() { return d; }
	   bool biger(Date&a);
	   void print() { cout << y << "年" << m << "月" << d << "日"<<endl; }
private:int y, m, d;
};
Date Date::operator+(int days)
{
	int ya = y, ma = m, da = d;
	while (days)
	{
		if (ma == 1 || ma == 3 || ma == 5 || ma == 7 || ma == 8 || ma == 10 || ma == 12)
		{
			if ((da + days )> 31)
			{
				days = days - 31 + da;
				da = 0;
				if (++ma > 12) {
					ya++;
					ma = ma - 12;
				}
			}
			else {
				da += days;
				days = 0;
			}
			
		}
		else if (ma==4||ma==6||ma==9||ma==11)
		{
			if ((da + days) > 30)
			{
				days = days - 30 + da;
				da = 0;
			/*	if (++m > 12) {
					y++;
					m = m - 12;
				}*/
				ma++;
			}
				else {
					da += days;
					days = 0;
				}
		}
		else if (ma==2&&Date(ya,ma,da).Isrun())
		{
			if ((da + days) > 29)
			{
				days = days - 29 + da;
				da = 0;
			/*	if (++m > 12) {
					y++;
					m = m - 12;
				}*/
				ma++;
			}
				else {
					da += days;
					days = 0;
				}
		}
		else 
		{
			if ((da + days) > 28)
			{
				days = days - 28 + da;
				da = 0;
				/*if (++m > 12) {
					y++;
					m = m - 12;
				}*/
				ma++;
			}
				else {
					da += days;
					days = 0;
				}
		}
			
	}
	return Date(ya, ma, da);
}
Date Date::operator-(int days)
{
	int ya = y, ma = m, da = d;
	while (1)
	{
		if (da - days > 0)
		{
			da = da - days;
			
			break;
		}
		else
		{
			if(--ma <= 0)
		{
			ya--;
			ma = 12;
		}
		
			if (ma == 1 || ma == 3 || ma == 5 || ma == 7 || ma == 8 || ma == 10 || ma == 12)
			{
				da += 31;
				
			}
			else if (ma == 4 || ma == 6 || ma == 7 || ma == 9 || ma == 11)
			{
				da += 30;
			/*	if (--m <= 0)
				{
					y--;
					m = 12;
				}*/
			//	m--;
			}
			else if (ma == 2 && Date(ya,ma,da).Isrun())
			{
				da += 29;
				/*if (--m <= 0)
				{
					y--;
					m = 12;
				}*/
			//	m--;
			}
			else
			{
				da += 28;
			/*	if (--m <= 0)
				{
					y--;
					m = 12;
				}*/
			//	m--;
			}
		}

	}
	return Date(ya, ma, da);
}
int Date::operator-(Date&b)
{
	int count = 0;
	//判断谁更大
	if (Date::biger(b ))//引用的引用??
	{
		int ya = y, ma = m, da = d;

		while (1) {
			if (da - b.getday() > 0)
			{
				count = da - b.getday();
				break;
			}
			else {
				if (--ma <= 0)
				{
					ya--;
					ma = 12;
				}
				if (ma == 1 || ma == 3 || ma == 5 || ma == 7 || ma == 8 || ma == 10 || ma == 12)
				{
					da+= 31;
					
				}
				else if (ma == 4 || ma == 6 || ma == 7 || ma == 9 || ma == 11)
				{
					da += 30;
				/*	if (--m <= 0)
					{
						y--;            //优化,不可能小于0其实只有m=1时才满足条件 可继续优化
						m = 12;
					}*/
				//	m--;
					
				}
				else if (ma == 2 && Date(ya,ma,da).Isrun())
				{
					da += 29;
				//	m--;
				}
				else
				{
					da += 28;
					//m--;
				}
			}
		}
		
		//月份产生的差
	
			if (ma-b.getmonth ()>= 0)
			{
				for (int i = b.getmonth(); i < ma; i++)
				{
					if (i == 1 || i == 3 || i== 5 || i== 7 || i == 8 || i == 10 || i == 12) count += 31;
					else if (i == 4 || i == 6 || i == 7 || i == 9 || i == 11)count += 30;
					else if (i == 2 && Date::Isrun())count += 29;
					else count += 28;
				}
			}
			else {
				ya--;
				for (int i = b.getmonth(); i < ma+12; i++)
				{
					if (i%12 == 1 || i%12 == 3 || i%12 == 5 || i%12 == 7 || i%12 == 8 || i%12 == 10 || i%12 == 0) count += 31;
					else if (i == 4 %12|| i%12 == 6 || i%12 == 7 || i%12 == 9 || i%12 == 11)count += 30;
					else if (i%12 == 2 && Date::Isrun())count += 29;
					else count += 28;
				}

			}
			//年的差
			for (int i = b.getyear(); i < y; i++)
			{
				if (Date(i, ma, da).Isrun())count += 366;
				else count += 365;
			}
			return count;
		}
	else return b.operator-(Date(y, m, d));
	}

bool Date::biger(Date&a)
{
	if (y > a.getyear()) return true;
	else if (y < a.getyear())return false;
	else if (m > a.getmonth()) return true;
	else if (m < a.getmonth())return false;
	else if (d > a.getday())return true;
	else return false;
}




P264/10.3

变成计算正方体,圆柱体和球的表面积和体积。要求抽象出一个公共的基类Body,把它作为抽象类,在该类中定义求表面积和体积的纯虚函数。抽象类中定义一个数据成员date,它可以作为球的半径,正方体的边长或圆柱体底面圆的半径。由这个抽象类派生出描述球,正方体和圆柱的3个具体类,在这3个类中都有计算表面积和体积的函数的具体实现。

#include<iostream>
#include<math.h>
#define PI 3.14
using namespace std;
class Geometric_shape
{
public:
	virtual double perimeter() = 0;
	virtual double area() = 0;
	virtual double volume() = 0;
	virtual void Show() = 0;
	
};
class Circle :public  Geometric_shape
{
public:Circle(double r = 0) :radios(r) {}
	   double perimeter() { return 2 * PI*radios; }
	   virtual double area() { return PI*radios*radios; }
	   virtual double volume() { return 0; }
	   void Show() {
		   cout << "图形为圆\t半径为" << radios << endl;
	   }

protected: double radios;
};


class Rectangle :public  Geometric_shape
{
public:Rectangle(double L = 0, double W = 0) :l(L), w(W) {}
	   double perimeter() { return 2 * (l + w); }
	   double area() { return l*w; }
	   double volume() { return 0; }
	   void Show() { cout << "图形为矩形\t 长和宽分别为" << l << "\t" << w << endl; }
protected:double l, w;

};
class Triangle : public    Geometric_shape
{
public:
	Triangle(double d1 = 0, double Y1 = 0, double Y2 = 0) :d(d1), y1(Y1), y2(Y2) {}
	double perimeter() { return d + y1 + y2; }
	double area();
	double volume() { return 0; }
	void Show() { cout << "图形为三角形\t三边分别长为:\t" << d << "\t" << y1 << "\t" << y2 << endl; }
protected: double d, y1, y2;
};
double Triangle::area()
{
	double l = perimeter() / 2;
	return sqrt(l*(l - d)*(l - y1)*(l - y2));
}
class  Box :public Rectangle
{
public:Box(double L = 0, double W = 0, double H = 0) :Rectangle(L, W), h(H) {}
	   double perimeter() { return 4 * h + 2 * Rectangle::perimeter(); }
	   virtual double area() { return Rectangle::area()*2+h*Rectangle::perimeter(); }
	   virtual double volume() { return h*Rectangle::area(); }
	   virtual void Show() { cout << "图形为长方体\t长宽高分别为:" << l << "\t" << w << "\t" << h << endl; }
private: double h;
};
class Cylinder :public Circle  //圆柱
{
public:
	Cylinder(double r = 0, double H = 0) :Circle(r), h(H) {}
	double area() { return 2*Circle::area()+h*Circle::perimeter(); }//biao面积
	double volume() { return h*Circle::area(); }
	void Show() { cout << "图形为圆柱/t底面半径和高分别为" << radios << "\t" << h << endl; }
private:double h;
};
class Cone :public Circle  //圆锥
{
public:Cone(double r = 0, double H = 0) :Circle(r), h(H) {}
	   double perimeter() { return Circle::perimeter(); }
	   double area() { return Circle::area(); }
	   double volume() { return (h*Circle::area()) / 3; }
	   void Show() { cout << "图形为圆锥\t 底面半径和高分别为" << radios << "\t" << h << endl; }
private:double h;
};
class T_pyramid :public Triangle  //三棱锥
{
public:T_pyramid(double D = 0, double Y1 = 0, double Y2 = 0, double H = 0) :Triangle(D, Y1, Y2), h(H) {}

	   double volume() { return (h*Triangle::area()) / 3; }
	   void Show() { cout << "图形为三棱锥 \t底面三角形三边长和高分别为" << d << "\t" << y1 << "\t" << y2 << endl; }
private:double h;
};
class  T_prism :public Triangle  //三棱柱
{
public: T_prism(double D = 0, double Y1 = 0, double Y2 = 0, double H = 0) :Triangle(D, Y1, Y2), h(H) {}

		double volume() { return (h*Triangle::area()) / 3; }
		void Show() { cout << "图形为三棱柱 \t底面三角形三边长和高分别为" << d << "\t" << y1 << "\t" << y2 << endl; }
private:double h;
};
class qiu:public Circle
{
public:
	qiu(double r) :Circle(r) {}
	virtual double area() { return 4 * Circle::area(); }
	virtual double volume() { return 4.0 / 3.0*PI*radios*radios*radios; }
	void show() { cout << "图形为半径为" << radios << "的球\n"; }
};

int main()
{
	Geometric_shape * gs[] = { new Box(6,8,3),new	Cylinder(10,3),new qiu(2) };
	for (int i = 0; i<3; i++)
	{
		gs[i]->Show();
		cout << endl;
	}
	int i;

	
	cout << "立体图形:" << endl;
	for (i = 0; i<3; i++)
	{
		
		cout << "图形表面积:" << gs[i]->area() << '\t';
		cout << "图形体积  :" << gs[i]->volume() << endl;
	}
	return 0;
}



P290/11.1

已知:
Void Sort(int a{ }),int size);
Void Sort(double a{ },int size);
是一个函数模板的两个实例,其功能是将数组a中的前size个元素按从小到大顺序排列。试设计这个函数模板。

#include<stdlib.h>
#include<iostream>
/*#include<stdlib.h>
在main函数结尾处(如果有return的话,在return之前)加上system("pause");*/
#include"class.h"
using namespace std;
int main()
{
	int a[6] = { 1,2,3,4,5,6 };
	char x[15] = "liaowenhua";
	double d[6] = { 2.5,5.2,3.4,5.6,4.0,4.0 };
	sort(a, 6);
	sort(x, 15);
	sort(d, 6);
	cout << a << x << d;
	system("pause"); return 0;
}

template <class T>
void sort(T* a, int size)  //数组传地址要用到指针不能直接用数组名
{
	T tem;
	int t ;
	for (int i = 0; i < size; i++)
	{
		t = i;
		for (int j = i; j < size; j++)
		{
			if (a[t] > a[j])t = j;
		}
		
		if (t != i) {
			tem = a[i];
			a[i] = a[t];
			a[t] = tem;
		}
	}
}


P290/11.2

设有如下的类声明:

Class Test
{
Public:
Void SetData1(int val) {data1=val;}
Void SetData2(double val) {data2=val;}
Int GetData1() { return data1;)}
Double GetData2() {return data2;}
Private:
Int data1;
Double data2;
}

试将此类声明改为类模板声明,使得数据成员data1和打她可以是任何类型

#include<iostream>
#include"Test.h"
using namespace std;
int main()
{
	Test<int, char> a;
	Test<int, int >b;//两个类型可以一样??
	Test<long, double>c;
	a.setdate1(10);
	a.setdate2('A');//用‘’号是一个字符“”两个加了“\0”
	b.setdate1(10);
	b.setdate2(15);
	c.setdate1(1202);
	c.setdate2(5.0);
	cout << a.getdate1() << " " << a.getdate2() << " " << b.getdate1() << " " << b.getdate2() << " " << c.getdate1() << " " << c.getdate2() << endl;
	system("pause");
	return 0;
}

#include<iostream>
using namespace std;
template<class T1,typename T2>
class Test
{
public:void setdate1(T1 d) { date1 = d; }
	   void setdate2(T2 d) { date2 = d; }
	   T1 getdate1() { return date1; }
	   T2 getdate2();
private: T1 date1;
		T2 date2;

};
template<class T1, typename T2>
T2 Test<T1, T2>::getdate2()
{
	return date2;
}



P290/11.3

栈是一种重要的数据结构,它是一种只允许在表的一端进行插入或删除操作的线性表。表中允许进行插入,删除操作的一端称为栈顶。表的另一端称为栈底。栈顶的当前位置是动态的,对栈顶当前位置的标记称为栈顶指针。当栈中没有数据元素时,称之为空栈。栈的插入操作通常称为进栈或入栈,栈的删除操作通常称为退栈或出栈。

#include<iostream>
#include"claa.h"
using namespace std;
int main()
{
	IStack<int> i;
	IStack<char> c;
	IStack<double> d;
	int x = 1, b;
	char y;
	double n;
	while (x)
	{
		cout << "插入  整型--3  字符--1  双精度--2  退出插入--0" << endl;
		cin >> x;
		switch (x)
		{
		case 1:
			cin >> y;
			c.Push(y); break;
		case 2:
			cin >> n;
			d.Push(n); break;
		case 3:
			cin >> b;
			i.Push(b);

		}
	}
	cout << "int char double 栈顶元素分别为:" << i.GetTop() << c.GetTop() << d.GetTop() << endl;
	cout << "删去栈顶元素后:" << endl;
	i.Pop();
	c.Pop();
	d.Pop();
	cout << "int char double 栈顶元素分别为:" << i.GetTop() << c.GetTop() << d.GetTop() << endl;
	system("puase");
	return 0;
}
#include<iostream>
using namespace std;
const int MaxSize = 100; // 栈中能保存的最多元素个数
template<class T>
class  IStack
{
public:
	IStack() { Top = -1; }         // 栈的构造函数
	void Push(T &n) { elem[++Top] = n; }    // 往栈顶增加元素
	void Pop();          // 从非空栈的栈顶删除一个元素
	T GetTop() {
		/* if(IStack<T>::Empty())
		1>e:\c++面向对象\第四期改1\第四期改1\is.h(15): warning C4715: “IStack<int>::GetTop”: 不是所有的控件路径都返回值
		cout<<"栈为空"<<endl;//
		else*/ return elem[Top];
	}      // 返回非空栈的栈顶元素
	bool Empty() { return Top == -1 ? true : false; }      // 判断栈是否为空
	int Size() { return Top; }         // 返回栈中元素的个数
	void ClearStack() { Top = -1; }  // 将栈清空
									 //~IStack(){};         // 栈的析构函数
private:
	T elem[MaxSize];  // 保存栈中各元素的数组
	int Top;          // 保存栈顶的当前位置
};
template<class T>
void IStack<T>::Pop()
{
	if (IStack<T>::Empty())
	{
		cout << "该盏为空!!" << endl;

	}
	else Top--;

}



P392/13.1

编写程序,重载运算符“<<”和“>>”,使用户能直接输入和输出复数。

#include<iostream>
using namespace std;
class complex
{
public:complex(double r1=0, double i1=0) :r(r1), i(i1) {}
	   friend ostream& operator<<(ostream& x, complex&a);//必须要用引用类型out
	   friend istream& operator>>(istream& x, complex&a);//返回类型一定要用引用
private:double r, i;
};

ostream& operator<<(ostream &x, complex&a)
{
	cout << a.r << "+" << a.i << "i" << endl;
	return x;
}
istream& operator>>(istream& x, complex&a)
{
	cout << "请输入真数部分,和虚数部分:" << endl;
	cin >> a.r >> a.i;
	return x;
}
int main()
{
	complex a, b;
	cin >> a >> b;
	cout << a << b;
	system("puase");
	return 0;
}


P392/13.3

编写一个程序,统计文本文件abc.txt中的字符个数,并给文件中的所有行加上行号,然后写到newabc.txt文件中。

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	fstream f;
	f.open("abc.txt");
	if (!f)
	{
		cout << "文件打开失败"<< endl;
		return 1;

	}
	cout << "输入保存数据:(0结束)" << endl;
	int a;
	cin >> a;
	while (a)
	{
		f << a;
		cin >> a;
	}
	a = 0;
	while (f.get())
		a++;
	fstream s;
	s.open("newabc.txt");
	if (!s)
	{
		cout << "文件打开失败" << endl;
		return 1;
	}
	char c;
	while (s.get(c))
		f.put(c);
	f.close();
	s.close();
	system("puase");
	return 0;
}


P392/13.6

编写一个程序:
(1)在二进制文件text.dat中写入10条记录,显示其内容。
(2)删除指定的第n条记录,并显示删除记录后的文件内容。
(3)按照记录号查询记录并显示结果。

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	fstream s;
	s.open("test.date", ios::in | ios::out | ios::binary);
	if (!s)
	{
		cout << "文件无法打开:" << endl;
		return 1;
	}
	char name[15];
	for (int i = 0; i < 10; i++)
	{
		cout << "请输入姓名:" << endl;
		cin >> name;
		s.write((char*)name, sizeof(char[15]));
	}
	s.seekp(0, ios::beg);
	for (int i = 1; i <= 10; i++)
	{
		s.read((char*)&s.tellp(), sizeof(char[15]));
		s.seekp(i * sizeof(char[15]));
	}
	cout << "请输入需要修改的数据记录号;(1--10)" << endl;
	int i;
	cin >> i;
	s.seekg((i-1) * sizeof(char[15]));
	cout << "姓名修改为:";
	cin >> name;
	s.write((char*)name, sizeof(char[15]));
	s.seekp(0, ios::beg);

	for (int i = 1; i <= 10; i++)
	{
		s.read((char*)&s.tellp(), sizeof(char[15]));
		s.seekp(i * sizeof(char[15]));
	}
	
	cout << "请输入需要查询的数据记录号;(1--10)" << endl;
	cin >> i;
	while (i) {
		cout << "请输入需要查询的数据记录号;(1--10  0退出)" << endl;
		cin >> i;
		s.seekg((i - 1) * sizeof(char[15]));
		s.read((char*)&s.tellp(), sizeof(char[15]));
	}
	s.close();
	system("puase");
	return 0;
}





  • 12
    点赞
  • 84
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值