当前位置:文档之家› 程序

程序

1五、编程题

(1)输入一个三位整数,将它反向输出。

【解答】

#include

using namespace std;

void main()

{ int x,i,j,k;

cout<<"please input x:";

cin>>x;

i=x/100;

j=(x-i*100)/10;

k=x-i*100-j*10;

cout<

}

(2)输入平面上某点横坐标x和纵坐标y,

若该点在由图2-8表示的方块区域内,则输出1;

否则,输出0。

图2-8 正方形

【解答】

#include

using namespace std;

void main()

{ float x,y,b;

cout<<"please input x,y:";

cin>>x>>y;

b=(-2<=x)&&(x<=2)&&(-2<=y)&&(y<=2);

cout<

}

21.输入三个整数,再将这三个整数按从小到大的顺序输出。

【解答】

#include

void main()

{

int a,b,c,t;

cout<<"a,b,c=";

cin>>a>>b>>c;

if(a>b){t=a;a=b;b=t;}

if(a>c){t=a;a=c;c=t;}

if(b>c){t=b;b=c;c=t;}

cout<

}

2.模拟剪刀、石头和纸游戏,用s表示剪刀,r表示石头,p表示纸。游戏规则为:剪刀剪纸,石头砸剪刀,纸包石头。两名游戏者分别输入s、r或p,按照游戏规则输出结果。

【解答】

#include

void main()

{

char first,second;

cout<<"First input(s,r or p):";

cin>>first;

cout<<"Second input(s,r or p):";

cin>>second;

switch(first)

{case 's':

switch(second)

{case 's':cout<<"Scissor ties scissor."<

case 'r':cout<<"Scissor is crushed by rock."<

case 'p':cout<<"Scissor cuts paper."<

default :cout<<"second input error!"<

}

case 'r':

switch(second)

{case 's': cout<<"Rock crushes scissor."<

case 'r': cout<<"Rock ties rock."<

case 'p': cout<<"Rock is wrapped by paper."<

default : cout<<"second input error!"<

}

case 'p':

switch(second)

{case 's':cout<<"Paper is cut by scissor."<

case 'r':cout<<"Paper wraps the rock."<

case 'p':cout<<"Paper ties paper."<

default :cout<<"second input error!"<

}

default:cout<<"First input error!"<

}

end:;

}

3.输入一个整数,输出该整数的所有素数因子。例如,输入120,输出为2、2、2、3和5。

【解答】

#include

void main()

{

int m,i = 2;

cout << "please input m:";

cin >> m;

while( i<=m )

if( m % i == 0 )

{

cout << i << " ";

m = m / i;

}

else i++;

cout <

}

4.找出100到200之间满足用3除余2且用5除余3且用7除余2的所有整数。

【解答】

#include

void main()

{

int i;

for( i=100; i<=200; i++ )

{

if ( ( i % 3 == 2) && ( i % 5 == 3 ) && ( i % 7 == 2 ) )

cout << i << endl;

}

}

5.如果一个整数恰好等于它的所有因子之和,则这个数称为完数。例如,6=1+2+3,所以6为完数。求1000之内的所有完数。

【解答】

#include

void main()

{

int i,j,s;

for( i=1; i<=1000; i++ )

{

s = 0;

for( j=1; j

if ( i % j == 0 ) s = s + j;

if ( i == s ) cout << i << endl;

}

}

6.在屏幕上输出如下图案:

*

* * *

* * * * *

* * * * * * *

* * * * * * * * *

【解答】

#include

void main()

{

int i,j,k;

for( i=1; i<=5; i++ )

{

for( k=1; k<=5-i; k++ ) cout << " ";

for( j=1; j<=2*i-1; j++ ) cout << "*";

cout << endl;

}

}

3(1)编写函数,定义两个unsigned short int型的参数,返回两个参数的商,其数据类型为short int。如果第二个参数为0,输出错误提示信息。

【源程序】

#include

short int Divider(unsigned short int a, unsigned short int b)

{

if (b == 0)

return -1;

else

return a/b;

}

int main()

{

unsigned short int one, two;

short int answer;

cout << "Enter two numbers.\n Number one: ";

cin >> one;

cout << "Number two: ";

cin >> two;

answer = Divider(one, two);

if (answer > -1)

cout << "Answer: " << answer;

else

cout << "Error, can't divide by zero!";

return 0;

}

运行结果为:

Enter two numbers.

Number one:8↙

Number two:2↙

Answer: 4

(2)编写函数,输入一个华氏温度,将华氏温度转换为摄氏温度输出,公式为C=(F-32)*5/9,其中F为华氏温度,C为摄氏温度。

【源程序】

#include

#include

void main()

{

double f,c,b;

cout<<"请输入华氏温度:"<

cin>>f;

cout<<"对应的摄氏温度为:"<

c=f-32;

b=5.00/9;

c=b*c;

cout<

}

运行结果为:

请输入华氏温度:

80↙

对应的摄氏温度为:

26.67

(3)编写函数,判断一个数是否是质数。

【源程序】

#include

#include

int prime(int i); //判断一个数是否是质数的函数

void main()

{

int i;

cout << "请输入一个整数:";

cin >> i;

if (prime(i))

cout << i << "是质数。" << endl;

else

cout << i << "不是质数。" << endl;

}

int prime(int i)

{

int j,k,flag;

flag = 1;

k = sqrt(i);

for (j = 2; j <= k; j++)

{

if(i%j == 0)

{

flag = 0;

break;

}

}

if (flag)

return 1;

else

return 0;

}

运行结果为:

请输入一个整数:1151↙

1151是质数。

(4)编写函数,求两个整数的最大公约数和最小公倍数。

【源程序】

#include

#include

int fn1(int i,int j); //求最大公约数的函数

void main()

{

int i,j,x,y;

cout << "请输入一个整数:";

cin >> i ;

cout << "请输入另一个整数:";

cin >> j ;

x = fn1(i,j);

y = i * j / x;

cout << i << "和" << j << "的最大公约数是:" << x << endl;

cout << i << "和" << j << "的最小公倍数是:" << y << endl;

}

int fn1(int i, int j)

{

int temp;

if (i < j)

{

temp = i;

i = j;

j = temp;

}

while(j != 0)

{

temp = i % j;

i = j;

j = temp;

}

return i;

}

运行结果为

请输入一个整数:120↙

请输入另一个整数:72↙

120和72的最大公约数是:24

120和72的最小公倍数是:360

(5)编写递归函数,计算x的y(y>0)次幂。

【源程序】

#include

long GetPower(int x,int y);

int main()

{

int number, power;

long answer;

cout << "Enter a number: ";

cin >> number;

cout << "To what power? ";

cin >> power;

answer = GetPower(number,power);

cout << number << " to the " << power << "th power is " <

return 0;

}

long GetPower(int x, int y)

{

if(y==1)

return x;

else

return (x * GetPower(x,y-1));

}

运行结果为:

Enter a number: 3↙

To what power? 4↙

3 to the 4th power is 81

(6)编写程序,要求输人四位数的年份、两位数的月份和日期,把它们按“年月日”的格式输出,并计算它是这一年的第几天。

【源程序】

#include

#include

daynum(int,int,int);

void date(int year,int month,int day)

{

cout<

cout<

cout<

cout<

cout<

}

daynum(int year,int month,int day)

{

int i,sum=0;

for(i=1;i

{

switch (i)

{

case 1: //1、3、5、7、8、10、12月有31天

case 3:

case 5:

case 7:

case 8:

case 10:

case 12:sum+=31;break;

case 4: //4、6、9、11月有30天

case 6:

case 9:

case 11:sum+=30;break;

case 2:if (((year%4==0 && year%100!=0)||year%400==0)) //闰年2月有29天

sum+=29;

else //平年2月有28天

sum+=28;

}

}

sum+=day;

return sum;

}

void main()

{

int year,month,day;

cout<<"请输入年/月/日:";

cin>>year>>month>>day;

date(year,month,day);

}

运行结果为:

请输入年/月/日:1984 03 05↙

1 9 8 4 0 3 0 5

65

4(1)编写程序,使用指针实现两个字符串的首尾连接(提示:将字符串str2接到str1的后面时,str1后面的'\0'被取消)。

#include

void strcat(char *str1,char *str2)

{

int i,m=0;

while(str1[m]!='\0') m++; //求数组str1长度

i=0;

while(str2[i]!='\0')

{

str1[m+i]=str2[i];

i++;

} //将字符串str2中有字符依次装入字符串str1中

str1[m+i]='\0';

}

void main()

{

char str1[16]="Chinese",str2[]="English";

strcat(str1,str2);

cout<

}

(2)编写程序,实现从多个字符串中寻找最长串。

#include

#include

char *maxstr(char *str[],int n)

{

int i,len,j=0;

len=strlen(str[j]); //求数组str[0]长度并赋给变量len

//从第2个字符串开始,只要字符串长度大于len,就赋给len并保留其下标

for(i=1;i

if(strlen(str[i])>len)

{

j=i;

en= strlen(str[i]) ;

}

return str[j];

}

void main()

{

char *a[4]={"China","England","American","Canada"};

cout<

}

(3)编写程序,实现两个字符串变量的交换。例如,交换前:

char *ap="hello";

char *bp="how are you";

则交换后使ap和bp指向的内容别是:

ap:how are you

bp:hello

#include

#include

void swap(char *p,char *q)

{

char temp[20];

strcpy(temp,p);

strcpy(p,q);

strcpy(q,temp);

}

void main()

{

char a[20]="hello",*ap=a;

char b[20]="how are you",*bp=b;

cout<<"交换前字符串值:\n";

cout<<"ap= "<

cout<<"bp= "<

swap(ap,bp);

cout<<"交换后字符串值:\n";

cout<<"ap= "<

cout<<"bp= "<

}

5(1)编写程序,实现从终端输入学生信息,根据学号查询并输出相应学生的信息。学生信息包括:学号no、姓

名name、政治分数politic、数学分数maths、英语分数english 和专业课分数special。

【参考代码】

结构体类型数组及指针的应用。

#include

struct stu

{

unsigned no;

char name[10];

int politic;

int maths;

int english;

int special;

};

void input(struct stu *q,int i)

{

cout<<"input student information:"<

for(int k=0;k

{

cin>>q->no;

cin>>q->name;

cin>>q->politic;

cin>>q->maths;

cin>>q->english;

cin>>q->special;

}

}

void enquire(struct stu *q,int j,unsigned a)

{

for(int i=0;i

if(q->no==a)

{

cout<no<<" ";

cout<name<<" ";

cout<politic<<" ";

cout<maths<<" ";

cout<english<<" ";

cout<special<<" ";

}

}

void main()

{

struct stu stud[30],*p=stud;

unsigned num;

input(p,30);

cout<<"input enquiring no:"<

cin>>num;

enquire(p,30,num);

}

(2)假设某公司有员工200人,员工的信息包括编号、姓名、基本工资、补贴、奖金和应扣款。编写程序,实现对员工工资信息的管理,包括查询和打印工资明细、应发工资和实发工资。

参考代码如下:

本题是在上题的基础上,加了一些控制功能,由此可见程序的编写其实是很实际简单的事。

#include

struct member

{

unsigned no;

char name[10];

float basewage;

float extrawage;

float bonus;

float decrease;

};

void input(member *q,int j)

{

cout<<"input member wage information:"<

for(int i=0;i

{

cout<<"no.: ";

cin>>q->no;cout<

cout<<"name:";

cin>>q->name;cout<

cout<<"basewage:";

cin>>q->basewage;cout<

cout<<"extrawage:";

cin>>q->extrawage;cout<

cout<<"bonus:";

cin>>q->bonus;cout<

cout<<"decrease:";

cin>>q->decrease;cout<

}

}

void enquire(member *q,int j,unsigned a)//查询函数

{

for(int i=0;i

if(q->no==a)

{

cout<<"no"<<"name

"<<"basewage"<<"extrawage";//表头

cout<<"bonus "<<"decrease "<<"totalwage ";

cout<<"realwage"<

cout<no<<" ";

cout<name<<" ";

cout<basewage<<" ";

cout<extrawage<<" ";

cout<bonus<<" ";

cout<decrease<<" ";

cout<basewage+q->extrawage+q->bonus<<" ";

cout<basewage+q->extrawage+q->bonus-q->decrease<

}

}

void print(member *q,int j,unsigned a)//打印函数

{

if(a==0)

{

cout<<"no "<<"name "<<"basewage "<<" extrawage";//表头

cout<<"bonus "<<"decrease "<<"totalwage "; //

cout<<"realwage"<

for(int i=0;i

{

cout<no<<" ";

cout<name<<" ";

cout<basewage<<" ";

cout<extrawage<<" ";

cout<bonus<<" ";

cout<decrease<<" ";

cout<basewage+q->extrawage+q->bonu s<<" ";

cout<basewage+q->extrawage+q->bonu s-q->decrease<

}

}

else

for(int i=0;i

if(q->no==a)

{

cout<<"no "<<"name "<<"basewage "<<"extrawage ";//表头

cout<<"bonus "<<"decrease "<<"totalwage "<<"realwage "

<

cout<no<<" ";

cout<name<<" ";

cout<basewage<<" ";

cout<extrawage<<" ";

cout<bonus<<" ";

cout<decrease<<" ";

cout<basewage+q->extrawage+q->bonu s<<" ";

cout<basewage+q->extrawage+q->bonu s-q->decrease<

}

}

void main()

{

member member[200],*p=member;

char n;int m;

input(p,200);

cout<<"enquire or print(e or p):";

cin>>n;

if(n=='e')

{

cout<<"enter the no.:"<

cin>>m;

enquire(p,200,m);

}

else if(n=='p')

{

int l;

cout<<"all or one(0 or one's no.):";

cin>>l;

print(p,200,l);

}

else

cout<<"WRONG OPERATOR!";

}

(3)编写程序,实现对学生和教师信息的输入、查询、删除和更新等操作。其中,学生信息包括学号、姓名、性别、班级和院系,教师信息包括编号、姓名、性别、职称、院系。

参考代码如下:

该数组长度设置应足够大,以便插入元素,删除元素只学号或代号置零,并不真正删除,相应的一些操作加浏览等要有条件判断使为零的学号或代号不显示。本题的插入操作是一次性的,可以试着更改程序,使其需要时再插入。

#include

struct member

{

unsigned no;

char name[10];

char sex;

char dep[20];

union{ //共同体,实现内存共享

char clas[20];

char position[20];

}level;

};

void construction(struct member *q,int j)//数组建设函数

{

cout<<"input person information(student's no>10000):"<

for(int i=0;i

{

cin>>q->no;

cin>>q->name;

cin>>q->sex;

cin>>q->dep;

if(q->no>10000)//学号大于10000,证明是学生

cin>>q->level.clas;

else

cin>>q->level.position;

}

}

void enquire(struct member *q,int j,unsigned a)//查询函数

{

for(int i=0;i

if(q->no==a)

{

cout<no<<" ";

cout<name<<" ";

cout<sex<<" ";

cout<dep<<" ";

if(a>10000)

cout<level.clas;

else

cout<level.position;

}

}

void alter(struct member *q,int j,unsigned a)//更新函数

{

for(int i=0;i

if(q->no==a)

{

cin>>q->no;

cin>>q->name;

cin>>q->sex;

cin>>q->dep;

if(q->no>10000)

cin>>q->level.clas;

else

cin>>q->level.position;

}

}

void browser(struct member *q,int j)//浏览函数

{

for(int i=0;i

if(q->no!=0) //不显示学号或代号为0的记录

{

cout<no<<" ";

cout<name<<" ";

cout<sex<<" ";

cout<dep<<" ";

if(q->no>10000)

cout<level.clas;

else

cout<level.position;

cout<

}

}

void delet(struct member *q,int j,unsigned a)//删除记录函数

{

for(int i=0;i

if(q->no==a)

{q->no=0;} //将学号或代号置0

}

void main()

{

member person[2];

unsigned num;

char x,y;

construction(person,2);

cout<<"want to operate?";//询问是否对数组操作

cin>>y;//'y'为操作,其他为不操作

while(y=='y')//循环询问操作

{

cout<<"want to enquire?"<

cin>>x;

if(x=='y')

{

cout<<"input no(student's no>10000):"<

cin>>num;

enquire(person,2,num);

cout<

}

cout<<"wangt to alter record?"<

cin>>x;

if(x=='y')

{

cout<<"input no(student's no>10000):"<

cin>>num;

alter(person,2,num);

cout<

}

cout<<"want to browser records?"<

cin>>x;

if(x=='y')

{

browser(person,2);

cout<

}

cout<<"want to delete record?"<

cin>>x;

if(x=='y')

{

cout<<"input no(student's no>10000):"<

cin>>num;

delet(person,2,num);

cout<

}

cout<<"want to operate?"<

cin>>y;//由变量y中的字符判断

}

}

6(1)构造一个日期时间类Timedate,实现对日期(年、月、

日)、时间(时、分、秒)的设置及输出。

解:

#include

#include

enum YR{Y2000,Y2001,Y2002,Y2003,Y2004,Y2005};

enum

MT{Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};

class Timedate{

private:

YR year;

MT month;

int date;

int hh;

int mm;

int ss;

public:

Timedate(){year=Y2000;month=Jan;date=1;hh=0; mm=0;ss=0;}

Timedate(YR a,MT b,int c)

{

year=a;

month=b;

date=c;

hh=12;mm=30;ss=0;

}

void getdate(YR &,MT &,int &);//使用引用一次取得3个数值

void gettime(int &,int &,int &);

void putdate(YR ,MT ,int );

void puttime(int ,int ,int );

void list();

};

void Timedate::getdate(YR &y,MT &m,int &d)

{

y=year;

m=month;

d=date;

}

void Timedate::gettime(int &a,int &b,int &c)

{

a=hh;

b=mm;

c=ss;

}

void Timedate::putdate(YR a,MT b,int c)

{

year=a;

month=b;

date=c;

}

void Timedate::puttime(int a,int b,int c){

hh=a;

mm=b;

ss=c;

}

void Timedate::list()//成员函数,直接访问私有的数据成员

{

cout<<"year/month/date :";

switch(year){

case Y2000:cout<<"2000";break;

case Y2001:cout<<"2001";break;

case Y2002:cout<<"2002";break;

case Y2003:cout<<"2003";break;

case Y2004:cout<<"2004";break;

case Y2005:cout<<"2005";break;

}

switch(month)

{

case Jan:cout<<'/'<<"Jan";break;

case Feb:cout<<'/'<<"Feb";break;

case Mar:cout<<'/'<<"Mar";break;

case Apr:cout<<'/'<<"Apr";break;

case May:cout<<'/'<<"May";break;

case Jun:cout<<'/'<<"Jun";break;

case Jul:cout<<'/'<<"Jul";break;

case Aug:cout<<'/'<<"Aug";break;

case Sep:cout<<'/'<<"Sep";break;

case Oct:cout<<'/'<<"Oct";break;

case Nov:cout<<'/'<<"Nov";break;

case Dec:cout<<'/'<<"Dec";break;

}

cout<<'/'<

cout<<"hour:minite:second :";

cout<

}

void main(int argc, char* argv[])

{

Timedate A(Y2004,Mar,3),B;

A.list();

B.list();

B.putdate(Y2005,Oct,18);

B.puttime(17,30,00);

B.list();

}

运行结果:

year/month/date :2004/Mar/3

hour:minute:second :12:30:0

year/month/date :2000/Jan/1

hour:minute:second :0:0:0

year/month/date :2005/Oct/18

hour:minute:second :17:30:0

(2)构造一个矩形类Rectangle,数据成员为矩形的左下角与右上角的坐标,并利用成员函数实现对矩形周长与面积的计算。

解:这里的矩形的4边分别与x轴y轴平行,为最简单的情况。注意参数有缺省值的函数的声明和定义格式。

#include

#include

class Rectangle

{

double left, top ;

double right, bottom;

public:

Rectangle(double l=0, double t=0, double r=0, double b=0);

~ Rectangle(){}; //析构函数,在此函数体为空

void Assign(double l,double t,double r,double b);

double getLeft(){ return left;} // 以下四个函数皆为内联成员函数

double getRight(){ return right;}

double getTop(){return top;}

double getBottom(){return bottom;}

void Show();

double Area();

double Perimeter();

};

// 构造函数,带缺省参数,缺省值为全0,在声明中指定

Rectangle::Rectangle(double l , double t, double r, double b) {

left = l; top = t;

right = r; bottom = b;

}

void Rectangle::Assign(double l, double t, double r, double b) //赋值

{

left = l; top = t;

right = r; bottom = b;

}

void Rectangle::Show()//成员函数直接使用私有的数据成员

{

cout<<"left-top point is

("<

cout<<"right-bottom point is

("<

}

double Rectangle::Area()

{

return fabs((right-left)*(bottom-top));

}

double Rectangle::Perimeter()

{

return 2*(fabs(right-left)+fabs(bottom-top));

}

int main()

{

Rectangle rect;

rect.Show();

rect.Assign(100,200,300,400);

rect.Show();

Rectangle rect1(0,0,200,200);

rect1.Show();

Rectangle rect2(rect1);

rect2.Show();

cout<<"面积"<

"<

return 0;

}

运行结果:

left-top point is (0,0)

right-bottom point is (0,0)

left-top point is (100,200)

right-bottom point is (300,400)

left-top point is (0,0)

right-bottom point is (200,200)

left-top point is (0,0)

right-bottom point is (200,200)

面积40000 周长800

(3)构造一个圆类Circle,属性为半径radius、圆周长和面积,实现根据输入的半径计算周长和面积并输出。要求定义以半径为参数、缺省值为0的构造函数,且周长和面积的计算在构造函数中实现。

解:通常所有数据成员都在构造函数中赋初值。拷贝构造函数以本类的引用为参数。

#include

#include

class Circle

{

double r,Area,Circumference;

public:

Circle(double a=0);

Circle(Circle &);

void SetR(double R);

double GetR(){return r;}

double GetAreaCircle(){return Area;}

double GetCircumference(){return Circumference;}

};

Circle::Circle(double a)

{

r=a;

Area=r*r*3.14159265;

Circumference=2*r*3.14159265;

}

Circle::Circle(Circle & cl)

{

r=cl.r;

Area=cl.Area;

Circumference=cl.Circumference;

}

void Circle::SetR(double R)

{

r=R;

Area=r*r*3.14159265;

Circumference=2*r*3.14159265;

}

int main()

{

Circle cl1(2),cl2,cl3=cl1;

cout<<"圆半径:"<

<<'\t'<<"圆面

积:"<

cl2.SetR(4);

cout<<"圆半径:"<

<<'\t'<<"圆面

积:"<

return 0;

}

运行结果:

圆半径:2 圆周长:12.5664 圆面积:

12.5664

圆半径:4 圆周长:25.1327 圆面积:

50.2655

(4)构造一个学校在册人员类Person,数据成员包括身份证号(IdPerson),姓名(Name),性别(Sex),生日(Birthday)和家庭住址(HomeAddress),实现对人员信息的录入和显示。

解:为指出构造函数等的调用,加了一些提示语句。

#include

#include

enum Tsex{mid,man,woman};

class Person

{

char IdPerson[19]; //身份证号,18位数字

char Name[20]; //姓名

Tsex Sex; //性别

int Birthday; //生日,格式1986年8月18日写作19860818

char HomeAddress[50]; //家庭地址public:

Person(char *,char *,Tsex,int,char *);

Person(Person &);

Person();

~Person();

void PrintPersonInfo();

void inputPerson();

//其他接口函数

};

Person::Person(char *id,char *name,Tsex sex,int birthday,char *homeadd)

{

cout<<"构造Person"<

strcpy(IdPerson,id);

strcpy(Name,name);

Sex=sex;

Birthday=birthday;

strcpy(HomeAddress,homeadd);

}

Person::Person()

{

cout<<"缺省构造Person"<

IdPerson[0]='\0';Name[0]='\0';Sex=mid;

Birthday=0;HomeAddress[0]='\0';

}

Person::Person(Person & Ps)

{

cout<<"拷贝构造Person"<

strcpy(IdPerson,Ps.IdPerson);

strcpy(Name,https://www.doczj.com/doc/237178494.html,);

Sex=Ps.Sex;

Birthday=Ps.Birthday;

strcpy(HomeAddress,Ps.HomeAddress);

}

Person::~Person()

{

cout<<"析构Person"<

}

void Person::inputPerson()

{

char ch;

cout<<"请输入身份证号,18位数字:"<

cin.getline(IdPerson,19);

cout<<"请输入姓名:"<

cin.getline(Name,20);

cout<<"请输入性别m或w:"<

cin>>ch;

if(ch=='m') Sex=man;

else Sex=woman;

cout<<"请输入生日,格式1986年8月18日写作19860818:"<

cin>>Birthday;

cin.get(); //吸收回车符,否则地址输不进去

cout<<"请输入地址:"<

cin.getline(HomeAddress,50);

}

void Person::PrintPersonInfo()

{

int i;

cout<<"身份证号:"<

if(Sex==man)cout<<"男"<<'\n';

else if(Sex==woman)cout<<"女"<<'\n';

else cout<<" "<<'\n';

cout<<"出生年月日:";

i=Birthday;

cout<

i=i%10000;

cout<

}

int main()

{

Person Ps1("320102*********","朱海鹏

",man,19811226,"南京市黄浦路1号"),

Ps2(Ps1),Ps3;

Ps1.PrintPersonInfo();

Ps2.PrintPersonInfo();

Ps3.inputPerson();

Ps3.PrintPersonInfo();

return 0;

}

运行结果:

构造Person

拷贝构造Person

缺省构造Person

身份证号:320102*********

姓名:朱海鹏

性别:男

出生年月日:1981年12月26日

家庭住址:南京市黄浦路1号

身份证号:320102*********

姓名:朱海鹏

性别:男

出生年月日:1981年12月26日

家庭住址:南京市黄浦路1号

请输入身份证号,18位数字:

320102*********↙

请输入姓名:

张红↙

请输入性别m或w:

w↙

请输入生日,格式1986年8月18日写作19860818:

19820405↙

请输入地址:

南京市幸福路12号↙

身份证号:320102*********

姓名:张红

性别:女

出生年月日:1982年4月5日

家庭住址:南京市幸福路12号

析构Person

析构Preson

析构Preson

7(1)先定义一个点类Point,包含数据成员x和y(坐标点)。以Point类为基类,派生出矩形类Rectangle和圆类Circle。假设矩形水平放置,在Rectangle类中,继承来的基类中的点作为矩形左下方的顶点,在派生类中增加数据成员长和宽;在Circle类中,继承来的基类中的点作为圆心,在派生类中增加数据成员半径。

要求判断给定点位于矩形和圆的什么位置。

解:

#include

#include

const double PI=3.1415926535;

class Point{

private:

double x,y;

public:

Point(){x = 0; y = 0; }

Point(double xv,double yv){x = xv;y = yv;}

Point(Point& pt){ x = pt.x; y = pt.y; }

double getx(){return x;}

double gety(){return y;}

double Area(){return 0;}

void Show(){cout<<"x="<

'<<"y="<

};

class Circle :public Point{

double radius;

public:

Circle(){radius = 0;}

Circle(double xv,double yv,double

vv):Point(xv,yv){radius = vv;}

Circle(Circle& cc):Point(cc){radius = cc.radius;} //拷贝构造函数

double Area(){return PI*radius*radius;}

void Show(){//注意怎样访问基类的数据成员cout<<"x="<

}

int position(Point &pt){

double distance =

sqrt((getx()-pt.getx())*(getx()-pt.getx())

+(gety()-pt.gety())*(gety()-pt.gety()));

double s=distance-radius;

if(s==0) return 0; //在圆上

else if(s<0) return -1;

//在圆内

else return 1;

//在圆外

}

};

class Rectangle:public Point{

double width,length;

public:

Rectangle(){width=0; length=0; }

Rectangle(double xv,double yv,double wv,double lv):Point(xv,xv) {

width = wv;

length= lv;

}

Rectangle(Rectangle& rr):Point(rr){

width = rr.width;

length = rr.length;

}

double Area(){return width*length;}

void Show(){

cout<<"x="<

cout<<"width="<

}

int position(Point &pt);

};

int Rectangle::position(Point &pt){

double s1,s2;

s1 = (pt.getx()-getx()); s2=(pt.gety()-gety());

if(((s1==0||s1==width)&&s2<=length)||((s2==0||s2 ==length)&&s1<=width)) return 0;

else if(s1

else return 1;

//1在矩形外

}

int main(){

Circle cc1(3,4,5),cc2,cc3(cc1);

Rectangle rt1(0,0,6,8),rt2,rt3(rt1);

Point p1(0,0),p2(6,8),p3(3,3),p4(8,4),p5(8,8);

cc1.Show();

cc2.Show();

rt1.Show();

rt2.Show();

cout<<"点p1:";

p1.Show();

cout<<"矩形rt3:"<<'\t';

rt3.Show();

switch(rt3.position(p1)){

case 0:cout<<"在矩形上"<

cout<<"圆cc3:"<<'\t';

cc3.Show();

switch(cc3.position(p1)){

case 0:cout<<"在圆上"<

}

cout<<"点p2:";

p2.Show();

cout<<"矩形rt3:"<<'\t';

rt3.Show();

switch(rt3.position(p2)){

case 0:cout<<"在矩形上"<

cout<<"圆cc3:"<<'\t';

cc3.Show();

switch(cc3.position(p2)){

case 0:cout<<"在圆上"<

}

cout<<"点p3:";

p3.Show();

cout<<"矩形rt3:"<<'\t';

rt3.Show();

switch(rt3.position(p3)){

case 0:cout<<"在矩形上"<

cout<<"圆cc3:"<<'\t';

cc3.Show();

switch(cc3.position(p3)){

case 0:cout<<"在圆上"<

}

cout<<"点p4:";

p4.Show();

cout<<"矩形rt3:"<<'\t';

rt3.Show();

switch(rt3.position(p4)){

case 0:cout<<"在矩形上"<

cout<<"圆cc3:"<<'\t';

cc3.Show();

switch(cc3.position(p4)){

case 0:cout<<"在圆上"<

}

cout<<"点p5:";

p5.Show();

cout<<"矩形rt3:"<<'\t';

rt3.Show();

switch(rt3.position(p5)){

case 0:cout<<"在矩形上"<

cout<<"圆cc3:"<<'\t';

cc3.Show();

switch(cc3.position(p5)){

case 0:cout<<"在圆上"<

case -1:cout<<"在圆内"<

case 1:cout<<"在圆外"<

}

return 0;

}

运行结果:

x=3 y=4 radius=5

x=0 y=0 radius=0

x=0 y=0 width=6 length=8

x=0 y=0 width=0 length=0

点p1:x=0 y=0

矩形rt3:x=0 y=0 width=6

length=8

在矩形上

圆cc3:x=3 y=4 radius=5

在圆上

点p2:x=6 y=8

矩形rt3:x=0 y=0 width=6

length=8

在矩形上

圆cc3:x=3 y=4 radius=5

在圆上

点p3:x=3 y=3

矩形rt3:x=0 y=0 width=6

length=8

在矩形内

圆cc3:x=3 y=4 radius=5

在圆内

点p4:x=8 y=4

矩形rt3:x=0 y=0 width=6

length=8

在矩形外

圆cc3:x=3 y=4 radius=5

在圆上

点p5:x=8 y=8

矩形rt3:x=0 y=0 width=6

length=8

在矩形外

圆cc3:x=3 y=4 radius=5

在圆外

(2)先定义一个Person类,包含数据成员姓名、性别和出生日期,以该类为基类,派生出学生类和职工类。在学生类中增加数据成员学号、成绩;在职工类中增加数据成员职工号和工资。其中,出生日期是日期类的对象。

要求计算学生的平均成绩和职工的平均工资。

#include

#include

#include

class Date

{

int year,month,day;

public:

Date(int y,int m,int d)

{

year=y;

month=m;

day=d;

}

void show_date()

{

cout<

}

};

class Person

{

protected:

char name[20];

char sex;

Date birthday;

public:

Person(char *nam,char s,int y,int m,int d):birthday(y,m,d)

{

strcpy(name,nam);

sex=s;

}

void show_person()

{

cout<

birthday.show_date();

}

};

class Student:public Person

{

public:

Student(char *nam,char s,int y,int m,int d,int cn,float sco):Person(nam,s,y,m,d),cno(cn),score(sco)

{

++count;

sum+=score;

avg=sum/count;

};

void show_student()

{

show_person();

cout<

}

void show_count_avg()

{

cout<

cout<

}

private:

int cno;

float score;

static int count;

static float sum;

static float avg;

};

class Employee:public Person

{

public:

Employee(char *nam,char s,int y,int m,int d,int cn,float sy):Person(nam,s,y,m,d),emyno(cn),salary(sy)

{

++count;

sum+=salary;

avg=sum/count;

};

void show_employee()

{

show_person();

cout<

}

void show_count_avg()

{

cout<

cout<

}

private:

int emyno;

float salary;

static int count;

static float sum;

static float avg;

};

int Student::count=0;

float Student::sum=0.0;

float Student::avg=0.0;

int Employee::count=0;

float Employee::sum=0.0;

float Employee::avg=0.0;

void main()

{

Student stu[3]={Student("Li Jing",'F',86,10,6,101,79),Student("Wang

Ping",'M',87,5,10,102,88),Student("Zhang

Li",'F',89,11,21,103,64)};

cout<

for(int i=0;i<3;i++)

stu[i].show_student();

cout<

e"<

stu[0].show_count_avg();

Employee emy[3]={Employee("Zhao

Ting",'F',75,7,15,201,2100),Employee("Wang

Peng",'M',74,3,1,202,1950),Employee("Li

Qiang",'M',77,12,19,203,2200)};

cout<

cout<

"sex"<

<"salary"<

for(i=0;i<3;i++)

emy[i].show_employee();

cout<

ry"<

emy[1].show_count_avg();

}

运行结果:

Student_name sex birthday cno score

Li Jing F 96/10/6 101 79

Wang Ping M 87/5/10 102 88

Zhang Li F 89/11/21 103 64

count avg_score

3 77

Employee_name sex birthday emyno

salary

Zhao Ting F 75/7/15 201

2100

Wang Peng M 74/3/1 202

1950

Li Qiang M 77/12/19 203

2200

count avg_salary

3 2083.33

8(1)几何形体的派生关系如下:

几何图形 geometric_shape)矩形 rectangle 圆 circle 三角形(trian 长方体 box)圆柱 cylinder)圆锥 cone)

三棱锥(t_pyr

平面图形有周长和面积,立体有表面积和体积。根据以上关

系的描述,实现计算平面图形的周长和面积、立体的表面积

和体积。

解:

运行时的多态性要用指针

#include

#include

const double PI=3.1415926535;

class Geometric_shape //几何图

{

public:

virtual double perimeter()=0; //定义纯

虚函数,求周长

virtual double area()=0; //定义纯

虚函数,求面积

virtual double volume()=0; //定义纯虚函

数,求体积

virtual void Show(){}; //声明虚

函数

};

class Circle :public Geometric_shape //圆

{

double radius;

public:

Circle(){radius = 0; } //定义构造函数

Circle(double vv){radius = vv;} //定义带参数的构造函数

double perimeter() //周长{return 2.0*PI*radius;}

double area() //面积{return PI*radius*radius;}

double volume() //体积{return 0;}

void Show()

{cout<<"radius="<

};

class Rectangle:public Geometric_shape//矩形

{

double width,length;

public:

Rectangle() //定义构造函数,设置长宽的初值

{width=0; length=0;}

Rectangle(double wid,double len) //定义带参数的构造函数

{

width = wid;

length= len;

}

Rectangle(Rectangle& rr)

{

width = rr.width;

length = rr.length;

}

double perimeter() //周长{return 2.0*(width+length);}

double area() //面积{return width*length;}

double volume() //体积{return 0;}

void Show()

{cout<<"width="<

};

class Triangle:public Geometric_shape //三角形

{

double a,b,c;

public:

Triangle() //定义构造函数

{a=0;b=0;c=0;}

Triangle(double v1,double v2,double v3)//定义带参数的构造函数

{a = v1;b = v2;c = v3;}

double perimeter() //周长

{return a+b+c;}

double area() //面积

{

double s=(a+b+c)/2.0;

return sqrt(s*(s-a)*(s-b)*(s-c));

}

double volume() //体积

{return 0;}

void Show()

{cout<<"a="<

};

class Box:public Rectangle //长方体

{

double height;

public:

Box() //定义构造函数

{height=0;}

Box(double wid,double len,double

heg):Rectangle(wid,len) //定义带参数的构造函数

{height=heg;}

double volume() //体积

{return area()*height;}

};

class Cylinder:public Circle //圆柱体

{

double height;

public:

Cylinder() //定义构造函数

{height=0;}

Cylinder(double vv,double heg):Circle(vv) //定义带参数的构造函数

{height=heg;}

double volume()

//体积

{return area()*height;}

};

class Cone: public Circle //圆锥

{

double height;

public:

Cone(){height=0;}

//定义构造函数

Cone(double vv,double

heg):Circle(vv){height=heg;} //定义带参数的构造函数

double volume(){return area()*height/3;} //体积

};

class T_pyramid:public Triangle //三棱锥

{

double height;

public:

T_pyramid()

//定义构造函数

{height=0;}

T_pyramid(double v1,double v2,double v3,double heg): //定义带参数的构造函数

Triangle(v1,v2,v3)

{height=heg;}

double volume()

//体积

{return area()*height/3;}

};

class T_prism:public Triangle

//三棱柱

{

double height;

public:

T_prism()

//定义构造函数

{height=0;}

T_prism(double v1,double v2,double v3,double heg): //定义带参数的构造函数

Triangle(v1,v2,v3)

{height=heg;}

double volume()

//体积

{return area()*height;}

};

void main()

{

Geometric_shape * gs;

Circle cc1(10);

Rectangle rt1(6,8);

Triangle tg1(3,4,5);

Box bx1(6,8,3);

Cylinder cl1(10,3);

Cone cn1(10,3);

T_pyramid tpy1(3,4,5,3);

T_prism tpr1(3,4,5,3);

cc1.Show();

//静态多态性

cout<<"圆周长:"<

cout<<"圆面积:"<

cout<<"圆体积:"<

gs=&rt1;

//动态多态性

gs->Show();

cout<<"矩形周长:"<perimeter()<<'\t';

cout<<"矩形面积:"<area()<<'\t';

cout<<"矩形体积:"<volume()<

gs=&tg1;

//动态多态性

gs->Show();

cout<<"三角形周长:"<perimeter()<<'\t';

cout<<"三角形面积:"<area()<<'\t';

cout<<"三角形体积:"<volume()<

gs=&bx1;

//动态多态性

gs->Show();

cout<<"长方体底周长:"<perimeter()<<'\t';

cout<<"长方体底面积:"<area()<<'\t';

cout<<"长方体体积:"<volume()<

gs=&cl1;

//动态多态性

gs->Show();

cout<<"圆柱体底周长:"<perimeter()<<'\t';

cout<<"圆柱体底面积:"<area()<<'\t';

cout<<"圆柱体体积:"<volume()<

gs=&cn1;

//动态多态性

gs->Show();

cout<<"圆锥体底周长:"<perimeter()<<'\t';

cout<<"圆锥体底面积:"<area()<<'\t';

cout<<"圆锥体体积:"<volume()<

gs=&tpy1;

//动态多态性

gs->Show();

cout<<"三棱锥底周长:"<perimeter()<<'\t';

cout<<"三棱锥底面积:"<area()<<'\t';

cout<<"三棱锥体积:"<volume()<

gs=&tpr1;

//动态多态性

gs->Show();

cout<<"三棱柱底周长:"<perimeter()<<'\t';

cout<<"三棱柱底面积:"<area()<<'\t';

cout<<"三棱柱体积:"<volume()<

}

运行结果:

radius=10

圆周长:62.8319 圆面积:314.159 圆体积:0

width=6 length=8

矩形周长:28 矩形面积:48 矩形体积:0

a=3 b=4 c=5

三角形周长:12 三角形面积:6 三角形体积:0

width=6 length=8

长方体底周长:28 长方体底面积:48

长方体体积:144

radius=10

圆柱体底周长:62.8319 圆柱体底面积:314.159 圆柱体体积:942.478

radius=10

圆锥体底周长:62.8319 圆锥体底面积:314.159 圆锥体体积:314.159

a=3 b=4 c=5

三棱锥底周长:12 三棱锥底面积:6 三棱锥体积:6

a=3 b=4 c=5

三棱柱底周长:12 三棱柱底面积:6 三棱柱体积:18

(2)定义哺乳动物类Mammal,以该类为基类派生出Dog类,二者均包含成员函数Speak(),通过基类指针访问基类和派生类中的同名函数Speak(),观察运行结果。

解:

源程序:

#include

class Mammal

{

public:

Mammal()

{ cout << "Mammal constructor...\n"; }

~Mammal()

{ cout << "Mammal destructor...\n"; }

virtual void Speak() const

{ cout << "Mammal speak!\n"; }

};

class Dog : public Mammal

{

public:

Dog()

{ cout << "Dog Constructor...\n"; }

~Dog() { cout << "Dog destructor...\n"; }

void Speak()const

{ cout << "Woof!\n"; }

};

void main()

{

Mammal a,*pDog;

pDog=&a;

pDog->Speak();

Dog d;

pDog=&d;

pDog->Speak();

}

程序运行输出:

Mammal Constructor...

Mammal speak!

Mammal Constructor...

Dog Constructor...

Woof!

Dog Destructor...

Mammal Destructor...

(3)定义点坐标类Point,重载++(自增)运算符实现横纵坐标值均加1,重载--(自减)运算符,实现横纵坐标值均减1。

解:

#include

class Point

{

public:

Point& operator++();

Point operator++(int);

Point& operator--();

Point operator--(int);

Point()

{ _x = _y = 0; }

int x()

{ return _x; }

int y()

{ return _y; }

private:

int _x, _y;

};

Point& Point::operator++()

{

_x++;

_y++;

return *this;

}

Point Point::operator++(int)

{

Point temp = *this;

++*this;

return temp;

}

Point& Point::operator--()

{

_x--;

_y--;

return *this;

}

Point Point::operator--(int)

{

Point temp = *this;

--*this;

return temp;

}

void main()

{

Point A;

cout << "A的值为:" << A.x() << " , " << A.y() <<

endl;

A++;

cout << "A的值为:" << A.x() << " , " << A.y() <<

endl;

++A;

cout << "A的值为:" << A.x() << " , " << A.y() <<

endl;

A--;

cout << "A的值为:" << A.x() << " , " << A.y() <<

endl;

--A;

cout << "A的值为:" << A.x() << " , " << A.y() <<

endl;

}

程序运行输出:

A的值为:0 , 0

A的值为:1 , 1

A的值为:2 , 2

A的值为:1 , 1

A的值为:0 , 0

(4)定义一个基类BaseClass,包括成员函数fn1()和fn2(),其中fn1()是虚函数;由它派生出类DerivedClass,也有成员函数fn1()和fn2()。在主程序中定义一个DerivedClass 的对象,分别用BaseClass和DerivedClass的指针来调用fn1()、fn2(),观察运行结果。

解:

#include

class BaseClass

{

public:

virtual void fn1();

void fn2();

};

void BaseClass::fn1()

{

cout << "调用基类的虚函数fn1()" << endl;

}

void BaseClass::fn2()

{

cout << "调用基类的非虚函数fn2()" << endl;

}

class DerivedClass : public BaseClass

{

public:

void fn1();

void fn2();

};

void DerivedClass::fn1()

{

cout << "调用派生类的函数fn1()" << endl;

}

void DerivedClass::fn2()

{

cout << "调用派生类的函数fn2()" << endl;

}

void main()

{

DerivedClass aDerivedClass;

DerivedClass *pDerivedClass = &aDerivedClass; BaseClass *pBaseClass = &aDerivedClass;

pBaseClass->fn1();

pBaseClass->fn2();

pDerivedClass->fn1();

pDerivedClass->fn2();

}

运行结果:

调用派生类的函数fn1()

调用基类的非虚函数fn2()

调用派生类的函数fn1()

调用派生类的函数fn2()

(5)定义一个基类BaseClass,包含虚析构函数;由它派生出类DerivedClass。在主程序中定义一个DerivedClass的对象,将该对象的地址赋给一个BaseClass的指针,观察虚析构函数是如何执行的。

解:

#include

class BaseClass

{

public:

virtual ~BaseClass()

{

cout << "~BaseClass()" << endl;

}

};

class DerivedClass : public BaseClass

{

public:

~DerivedClass()

{

cout << "~DerivedClass()" << endl;

}

};

void main()

{

BaseClass* bp = new DerivedClass;

delete bp;

}

运行结果:

~DerivedClass()

~BaseClass()

9(1)编写程序,实现将文件file2.txt中的内容拷贝到文件file1.txt中。

答案:

参考代码

#include

#include

void main()

{

ofstream ouf;

ifstream inf;

ouf.open("file1.txt");

if(!ouf)

{

cout<<"open file1.txt errors!"<

return;

}

inf.open("file2.txt");

if(!inf)

{

cout<<"open file2.txt errors!"<

return;

}

char ch;

while(inf.get(ch))

ouf.put(ch);

ouf.close();

inf.close();

}

提示:首先在当前目录下建立文件file2.txt并输入数据。

(2)编写程序,将某班学生的学号、姓名、三门功课的成绩存入file.txt文件,然后显示在屏幕上。

#include

#include

struct infor

{

unsigned num;

char name[15];

float sco1;

float sco2;

float sco3;

}stu[3];

void main()

{

ofstream ouf("infor.txt");

if(!ouf)

{

cout<<"open infor.txt errors!"<

return;

}

for(int i=0;i<3;i++)

{

cout<<"input num:";cin>>stu[i].num;cout<

cout<<"input name:";cin>>stu[i].name;cout<

cout<<"input lecture1 score:";cin>>stu[i].sco1;cout<

cout<<"input lecture2 score:";cin>>stu[i].sco2;cout<

cout<<"input lecture3 score:";cin>>stu[i].sco3;cout<

ouf.write((char*)&stu[i],sizeof(stu));

}

ouf.close();

ifstream inf("infor.txt");

if(!inf)

{

cout<<"open infor.txt errors!"<

return;

}

for(int j=0;j<3;j++)

{

inf.read((char*)&stu[j],sizeof(stu));

cout<

cout<

}

inf.close();

}

运行结果:

input num:1001↙

input name:a↙

input lecture1 score:65↙

input lecture2 score:75↙

input lecture3 score:85↙

input num:1002↙

input name:b↙

input lecture1 score:79↙

input lecture2 score:82↙

input lecture3 score:66↙

input num:1003↙

input name:c↙

input lecture1 score:77↙

input lecture2 score:68↙

input lecture3 score:95↙

1001 a 65 75 85

1002 b 79 82 66

1003 c 77 68 95

(3)编写程序,统计文件file.txt中内容的行数和字符数。

#include

#include

void main()

{

ifstream inf("infor.txt");

if(!inf)

{

cout<<"open infor.txt errors!"<

return;

}

char ch,buf[80];

int i=0,j=0;

while(!inf.eof())

{

inf.get(ch);

if(ch!='\n')

{

buf[i]=ch;

i++;

}

else

j++;

}

cout<<"character num:"<

cout<<"line num:"<

inf.close();

}

运行结果:

character num:28

line num:6

(4)对第2题的程序进行完善,使其具有插入、删除、查询功能。

答案:

这是一个比较综合的例子,先把复杂的程序分解成几

个模块,每个模块编写一个程序片段,以下是参考代码。

#include

#include

struct infor

{

unsigned num;

char name[15];

float sco1;

float sco2;

float sco3;

}stu[3];

void main()

{

ofstream ouf("infor.txt");

if(!ouf)

{

cout<<"open infor.txt errors!"<

return;

}

for(int i=0;i<3;i++)

{

cout<<"input num:";cin>>stu[i].num;cout<

cout<<"input name:";cin>>stu[i].name;cout<

cout<<"input lecture1

score:";cin>>stu[i].sco1;cout<

cout<<"input lecture2

score:";cin>>stu[i].sco2;cout<

cout<<"input lecture3

score:";cin>>stu[i].sco3;cout<

ouf.write((char*)&stu[i],sizeof(stu));

}

ouf.close();

ifstream inf("infor.txt");

if(!inf)

{

cout<<"open infor.txt errors!"<

return;

}

for(int j=0;j<3;j++)

{

inf.read((char*)&stu[j],sizeof(stu));

cout<

cout<

"<

}

inf.close();

char ch;

int n=3;

cout<<"do you want to delete record?"<

cin>>ch;

if(ch=='y')

{

int a;

cout<<"input num that will be delete:";

cin>>a;

ouf.open("infor.txt");

if(!ouf)

{

cout<<"open infor.txt errors!"<

return;

}

for(i=0;i

{

if(i!=a-1)

ouf.write((char*)&stu[i],sizeof(infor));

}//把不删除的记录写到文件中

n=n-1;

ouf.close();

}

inf.open("infor.txt"); //以输入方式打开

if(!inf)

{

cout<<"open infor.txt errors!"<

return;

}

cout<<"the record be deleted is:"<

for(j=0;j

{

inf.read((char*)&stu[j],sizeof(infor));

cout<

"<

}

inf.close();

cout<<"do you want to enquire a record?"<

infor stud; cin>>ch; if(ch=='y') {

int k;cout<<"input num that will be enquired:"; cin>>k;

inf.open("infor.txt"); if(!inf) {

cout<<"open infor.txt errors!"<

inf.seekg((k-1)*sizeof(infor));

inf.read((char*)&stud,sizeof(infor));

cout<

"<

inf.close(); }

cout<<"do you want to insert a record?"<

记录

cin>>ch; if(ch=='y') {

ofstream ouf;

ouf.open("infor.txt",ios::app);//在文件中的内容后

输出,不清楚数据

if(!ouf) {

cout<<"open infor.txt errors!"<

cout<<"input a new record:"<>stud.num; cout<

cout<<"input name:"; cin>>https://www.doczj.com/doc/237178494.html,; cout<

cout<<"input lecture1 score:"; cin>>stud.sco1; cout<

cout<<"input lecture2 score:"; cin>>stud.sco2; cout<

cout<<"input lecture3 score:"; cin>>stud.sco3; cout<

ouf.write((char*)&stud,sizeof(infor)); ouf.close(); n=n+1; //

记录数增1,也可以用循环语句插入多条记录

ifstream inf1("infor.txt"); if(!inf1) {

cout<<"open infor.txt errors!"<

inf1.seekg((n-1)*sizeof(infor));

inf1.read((char*)&stud,sizeof(infor)); cout<<"the new inserted record:"<

"<

inf1.close(); ifstream inf2;

inf2.open("infor.txt"); if(!inf2) {

cout<<"open infor.txt errors!"<

cout<<"the whole record:"; cout<

for(j=0;j

inf2.read((char*)&stud,sizeof(infor));

cout<

"<

inf2.close(); } }

运行结果:

input num:1001↙ input name:a ↙

input lecture1 score:65↙ input lecture2 score:75↙ input lecture3 score:85↙ input num:1002↙ input name:b ↙

input lecture1 score:79↙ input lecture2 score:82↙ input lecture3 score:66↙ input num:1003↙ input name:c ↙

input lecture1 score:77↙ input lecture2 score:68↙ input lecture3 score:95↙ 1001 a 65 75 85 1002 b 79 82 66 1003 c 77 68 95

do you want to delete record? y ↙

input num that will be delete:3↙ the record be deleted is: 1001 a 65 75 85 1002 b 79 82 66

do you want to enquire a record? y ↙

input num that will be enquired:2↙ 1002 b 79 82 66

do you want to insert a record? y ↙

input a new record: input num:1004↙ input name:d ↙

input lecture1 score:78↙ input lecture1 score:88↙ input lecture1 score:86↙ the new inserted record: 1004 d 78 88 86 the whole record:3 1001 a 65 75 85 1002 b 79 82 66 1004 d 78 88 86

10学校的人事处保存了有关学生的部分信息,包括学号、姓名、年龄和住址,教务处也保存了学生的部分信息包括学号、姓名、性别和成绩,为方便管理,两个部门的学生数据信息都采用student 作为类名。现要求在全校的学生数据管理程序中调用这两个部门的学生数据,显示学生的相关信息。

提示:使用命名空间实现。 参考代码如下:

//admin.h

#include #include using namespace std; namespace admin {

class student {

public:

student(int n,string nam,int a,string add):

num(n),name(nam),age(a),a

ddress(add){}

void showData(); private: int num;

string name;

int age;

string address;

};

void student::showData()

{

cout<<"number:"<

cout<<"name:"<

cout<<"age:"<

cout<<"address:"<

}

}

//edu.h

#include

#include

using namespace std;

namespace edu

{

class student

{

public:

student(int n,string nam,char s,float sco): //constructor function

num(n),name(nam),se

x(s),score(sco){}

void showData();

private:

int num;

string name;

char sex;

float score;

};

void student::showData()

{

cout<<"number:"<

cout<<"name:"<

cout<<"sex:"<

cout<<"score:"<

}

}

//12-3.cpp

#include

#include"admin.h"

#include"edu.h"

using namespace std;

int main()

{

admin::student

stud1(1001,"zhangpeng",17,"changjiang road 8#");

stud1.showData();

edu::student stud2(1001,"zhangpeng",'M',98.5);

stud2.showData();

return 0;

}

运行结果:

number:1001

name:zhangpeng

age:17

address:changjiang road 8#

number:1001

name:zhangpeng

sex:M

score:98.5

相关主题
文本预览