2019BJFU C++实验习题(完结)

各位学弟学妹,注意独立思考w(゚Д゚)w

1.图书类

发布时间: 2019年3月1日 22:34   时间限制: 1000ms   内存限制: 128M

以下是图书类Book的声明,缺少实现部分,请实现成员函数并编写main函数测试Book类。

class Book

{

private:

   char *name;                //书名

   char *author;              //作者

   int sale;                  //销售量

public:

   Book();                               //无参构造函数

   Book(char *a, char *b, int c);         //有参构造函数

   Book(const Book &);                   //拷贝构造函数

   void print();                          //显示数据

   ~Book();                              //析构函数

};

在main函数中,我们输入三行数据,第一行是书的名称(长度不超过100,可能含有空格),第二行是作者的名字(长度不超过100,可能含有空格),第三行是销量(整数类型)。

类中有三个对应的成员变量,分别为name,author和sale,利用题目中所给的构造函数来实例化对象,需要注意的是,题目中有三个构造函数,分别是有参构造函数和无参构造函数还有拷贝构造函数,在此我们特别声明,当输入的name,author和sale都为-1的时候,请使用无参构造函数来实例化对象,此时我们将name的默认值设置为"No name",author的默认值设置为"No author",sale的默认值设置为0.当输入都为0的时候,我们使用拷贝构造函数来处理,这种情况具体在main函数中的实现是这样的:

Book bk1;

Book bk2(bk1);

bk2.print();

其他情况下一律用有参数的构造函数来构造对象。

使用类中的void print()方法来输出一定格式的字符串,详见样例。

The Art of Computer Programming
Donald Ervin Knuth
1000
Name: The Art of Computer Programming Author: Donald Ervin Knuth Sale: 1000

1、注意输出格式,每个图书的信息占一行,信息的项目之间用 分隔,最后以 换行。Name:,Author:,Sale:后面都有一个空格

2、输入书名和作者时,因为会含有空格,请用gets()函数

请注意,必须要用类(class)来实现代码,否则不得分

AC代码:

1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<iomanip>
 6 using namespace std;
 7 class Book
 8 
 9 {
10 
11 private:
12 
13    char *name;                //书名
14 
15    char *author;              //作者
16 
17    int sale;                  //销售量
18 
19 public:
20 
21    Book();                               //无参构造函数
22 
23    Book(char *a, char *b, int c);         //有参构造函数
24 
25    Book(const Book &);                   //拷贝构造函数
26 
27    void print();                          //显示数据
28 
29    ~Book();                              //析构函数
30 
31 };
32 
33 Book::Book()
34 {
35     name= new char[10];
36     strcpy(name,"No name");
37     author=new char[10];
38     strcpy(author,"No author");        
39     sale=0;
40 }
41 
42 Book::Book(const Book &x)
43 {
44     name=new char[strlen(x.name)+1];
45     strcpy(name,x.name);
46     author=new char[strlen(x.author)+1];
47     strcpy(author,x.author);
48     sale=x.sale;
49 }
50 
51 Book::Book(char *a,char*b,int c)
52 {
53     name=new char[strlen(a)+1];
54     strcpy(name,a);
55     author=new char[strlen(b)+1];
56     strcpy(author,b);
57     sale=c;
58 }
59 void Book::print()
60 {
61     cout<<"Name: "<<name<<"	"<<"Author: "<<author<<"	"<<"Sale: "<<sale<<endl;
62 }
63 
64 
65 Book::~Book()
66 {
67     delete[] name;
68     delete[] author;
69 }
70 int main()
71 {
72     char name1[103],name2[103];
73     int num;
74     gets(name1);
75     gets(name2);
76     cin>>num;
77     
78     if(strcmp(name1,"-1")==0&&strcmp(name2,"-1")==0&&num==-1)
79     {
80         Book bk1;
81         bk1.print();
82     }
83     else if(strcmp(name1,"0")==0&&strcmp(name2,"0")==0&&num==0)
84     {
85         Book bk1;
86         Book bk2(bk1);
87         bk2.print();
88     }
89     else 
90     {
91         Book bk1(name1,name2,num); 
92         bk1.print();  
93     }
94     return 0;
95 }
View Code

2.计算圆面积

发布时间: 2019年3月1日 22:31   时间限制: 1000ms   内存限制: 128M

 编写一个圆类Circle,实现半径的输入、面积的计算和输出。

输入一行,输入圆的半径(double类型)。

输出一行,输出圆的面积(保留小数点后两位)。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<iomanip>
 6 using namespace std;
 7 
 8 const double PI=acos(-1.0);
 9 class Circle{
10     private:
11         double r;
12     public:
13         void print();
14         void input();        
15 };
16 void Circle::input()
17 {
18     cin>>r;
19 }
20 void Circle::print()
21 {
22     cout<<setiosflags(ios::fixed)<<setprecision(2);
23     cout<<PI*r*r<<endl;
24 }
25 int main()
26 {
27     Circle c;
28     c.input();
29     c.print();
30     return 0;
31 }
View Code

3.旅馆人数统计

发布时间: 2019年3月1日 22:41   最后更新: 2019年3月1日 22:43   时间限制: 1000ms   内存限制: 128M

编写程序,统计某旅馆住宿客人的总数。要求输入客人的姓名,输出客人的编号(按先后顺序自动生成)、姓名以及总人数。使用如下main函数对程序进行测试

int main(){

 Hotel h[100];

 h[0].add("Susan");

 h[1].add("Peter");

 h[2].add("John");

 h[3].add("Mary");

 h[4].add("Alice");

 string name;

 cin>>name;

 for(int i=0;i<Hotel::getTotal();i++) {

  if(h[i].getName()==name){

   h[i].print();

   break;

  }

 }

 return 0;

}

输入一行,输入客人的姓名(不超过100个字符的由英文大小写字母组成的字符串)。

输出一行,输出客人的编号,姓名及总人数,空格分隔。

Peter
2 Peter 5
#include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<iomanip>
 6 #include<string>
 7 using namespace std;
 8 
 9 class Hotel{
10     private :
11         string person;
12         int num;
13     public:
14         static int totalnum;
15         string getName();
16         void add(string s);
17         void print();
18         static int getTotal();
19 };
20 
21 string Hotel::getName()
22 {
23     return person;
24 }
25 
26 void Hotel::add(string s)
27 {
28     totalnum++;
29     num=totalnum;
30     person=s;
31 }
32 
33 void Hotel::print()
34 {
35     cout<<num<<" "<<person<<" "<<totalnum<<endl;
36 }
37 int Hotel::getTotal()
38 {
39     return totalnum;
40 }
41 
42 int Hotel::totalnum=0;
43 
44 int main(){
45 
46  Hotel h[100];
47 
48  h[0].add("Susan");
49 
50  h[1].add("Peter");
51 
52  h[2].add("John");
53 
54  h[3].add("Mary");
55 
56  h[4].add("Alice");
57 
58  string name;
59 
60  cin>>name;
61 
62  for(int i=0;i<Hotel::getTotal();i++) {
63 
64   if(h[i].getName()==name){
65 
66    h[i].print();
67 
68    break;
69 
70   }
71 
72  }
73 
74  return 0;
75 
76 }
View Code

Person类

发布时间: 2019年3月1日 22:45   时间限制: 1000ms   内存限制: 128M

实现一个Person类,通过以下测试:

int main(){

const Person Amy("Amy","Beijing Forestry Univeristy");   //姓名和地址

const Person copy_Amy(Amy);

cout<<"Name: "<<Amy.getName()<<" Address: "<<Amy.getAddress()<<endl; 

cout<<" This is a copy of Amy: ";

cout<<"Name: "<<copy_Amy.getName()<<" Address: "<<copy_Amy.getAddress()<<endl; 

return 0;

}

Name: Amy
Address: Beijing Forestry Univeristy

This is a copy of Amy:
Name: Amy
Address: Beijing Forestry Univeristy

同要求的输出

不能修改main函数,否则不得分

虽然我想说这种题目,没有输入的,直接cout样例输出就可以AC了,但是老师也不傻啊233333毕竟算入平时成绩的orz

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<string>
using namespace std;
class Person{
    private:
        string name;
        string school;
    public:
        Person(const Person&);
        Person(string n,string s);
        string getName()const;
        string getAddress()const;
};

Person::Person(string n,string s)
{
    name=n;
    school=s;
}

Person::Person(const Person &x)
{
    name=x.name;
    school=x.school;
}

string Person::getName()const
{
    return name;
}

string Person::getAddress()const
{
    return school;
}

int main(){

const Person Amy("Amy","Beijing Forestry Univeristy");   //姓名和地址

const Person copy_Amy(Amy);

cout<<"Name: "<<Amy.getName()<<"
Address: "<<Amy.getAddress()<<endl; 

cout<<"
This is a copy of Amy:
";

cout<<"Name: "<<copy_Amy.getName()<<"
Address: "<<copy_Amy.getAddress()<<endl; 

return 0;

}
View Code

 

日期相差天数(选做)


发布时间: 2019年3月1日 22:46   时间限制: 1000ms   内存限制: 128M


定义日期类Date包含年、月、日三个数据成员,编写一个友元函数,求两个日期之间相差的天数(日期不分前后顺序)。

输入两行,为两个日期data1和data2,格式见样例。

输出一行,两个日期间相差的天数。

2008-9-1
2015-4-1
2403

公历的平年是365天,闰年是366天。置闰的方法是能被4整除的年份在 

2月加一天,但能被100整除的不闰,能被400整除的又闰。因此,像1600、2000、2400年都是闰年,而1700、1800、1900、2100年都是平年。公元前1年,按公历也是闰年。

因此,对于从公元前1年(或公元0年)12月31日到某一日子的年份Y之间的所有整年 

中的闰年数,就等于 [(Y-1)/4] - [(Y-1)/100] + [(Y-1)/400]。

请注意,必须要用类(class)来实现代码,否则不得分。


 ..

1 #include <iostream>
  2 #include <algorithm>
  3 #include <cmath>
  4 #include <stdio.h>
  5 using namespace std;

 17 class date{
 18     private:
 19         int y,m,d;
 20     public:
 21         date(int a,int b,int c)
 22         {
 23             y=a;
 24             m=b;
 25             d=c;
 26         }
 27         static int noyear(date &h)
 28         {
 29             int no=0;
 30                  for(int i=1;i<h.m;i++)
 31                 {
 32                     switch(i)
 33                     {
 34                         case 1:no=no+31;break;
 35                         case 2:{
 36                             if((h.y%100!=0&&h.y%4==0)||(h.y%400 == 0))
 37                                 no=no+29;
 38                             else
 39                                 no=no+28;
 40                             break;
 41                         }
 42                         case 3:no=no+31;break;
 43                         case 4:no=no+30;break;
 44                         case 5:no=no+31;break;
 45                         case 6:no=no+30;break;
 46                         case 7:no=no+31;break;
 47                         case 8:no=no+31;break;
 48                         case 9:no=no+30;break;
 49                         case 10:no=no+31;break;
 50                         case 11:no=no+30;break;
 51                     //    case 12:no1=no1+31;break;
 52                     }
 53                 }
 54                 no=no+h.d;
 55                 return no;
 56         }
 57         static int ans(date &p,date &q)
 58         {
 59             int answer,no1,no2;
 60             //如果年相同,月也相同:Return | day1 - day2
 61             if(p.y==q.y&&p.m==q.m)
 62             {
 63                 answer=p.d-q.d;
 64                 if(answer<0)
 65                     answer=-answer;
 66             }
 67             //如果年相同,月不同:D1 = date1是该年的第几天  D2 = date2是该年的第几天
 68             else if(p.y==q.y&&p.m!=q.m)//以防万一 
 69             {
 70                 
 71                 no1=noyear(p);
 72                 no2=noyear(q);
 73                 answer=no1-no2;
 74                 if(answer<0)
 75                     answer=-answer;
 76             }
 77             //如果年份不同:D1 = 年份小的日期,离年底还有多少天 D2 = 年份大的日期是这年的第几天
 78             //D3 = 两个日期之间相差多少个整年,共有多少天
 79             else if(p.y!=q.y) 
 80             {
 81                 int leap=0;
 82                 //计算两个日期之间相差多少个整年,其中有多少个闰年。
 83                 int maxy=p.y>q.y?p.y:q.y;
 84                 int miny=p.y<q.y?p.y:q.y;
 85                 int cnty=0;
 86                 for(int i=miny+1;i<maxy;i++)
 87                 {
 88                     if((i%100!=0&&i%4==0)||(i%400 == 0))
 89                         leap=leap+1;
 90                     cnty=cnty+1;
 91                 } 
 92                 //比较年份,年份小距年底的日期,年份大是这年第几天。
 93                 no1=noyear(p);
 94                 no2=noyear(q);
 95                 
 96                 if(p.y<q.y)
 97                 {
 98                     if((p.y%100!=0&&p.y%4==0)||(p.y%400 == 0))
 99                         no1=366-no1;
100                     else
101                         no1=365-no1;
102                 }
103                 else{
104                         if((q.y%100!=0&&q.y%4==0)||(q.y%400 == 0)) 
105                             no2=366-no2;
106                         else
107                             no2=365-no2;                            
108                 }
109                 
110                 answer=no1+no2+leap*366+(cnty-leap)*365;
111             }
112             return answer;
113         }
114 };
115 int main()
116 {
117     int a,b,c;
118     scanf("%d-%d-%d",&a,&b,&c);
119     date d1(a,b,c);
120     scanf("%d-%d-%d",&a,&b,&c);
121     date d2(a,b,c);
122     cout<<date::ans(d1,d2)<<endl;
123     return 0;
124 }
View Code

表面积和体积

发布时间: 2019年3月19日 10:38   最后更新: 2019年3月19日 10:42   时间限制: 1000ms   内存限制: 128M

编写程序计算长方体、圆柱体和球的表面积和体积。要求先定义一个抽象类Shape如下:

class Shape {

public:

         Shape() {}

         virtual double area() = 0;

         virtual void input() = 0;

         virtual double volume() = 0;

         virtual ~Shape() {}

};

使用Shape类派生出长方体类、圆柱体类、球类,在这些类里分别实现继承的纯虚函数。使用如下代码测试运行。

void work(Shape *s) {
    s->input();
    cout << s->area() << " " << s->volume() << endl;
    delete s;
}

int main() {

char c;

while (cin >> c) {

                   switch (c) {

                   case 'c': work(new Cuboid()); break;

                   case 'y': work(new Cylinder()); break;

                   case 'q': work(new Ball()); break;

                   default: break;

                   }

}

return 0;

}

输入包含多行,每行首先是一个字符’c’,’y’,’q’,分别表示输入长方体、圆柱体或球的信息,接下来是对应的输入。

每行输入对应一行输出,表示该形状的表面积和体积,以空格分隔。

c 3 4 5
y 3 5
q 5
94 60
150.796 141.372
314.159 523.599

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <string.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <cctype>
#include <iomanip>
using namespace std;
const double pi=acos(-1.0);
class Shape {
    protected:
        int c,k,g;
        double x,y,z;
        double a,v;
public:

         Shape() {}

         virtual double area() = 0;

         virtual void input() = 0;

         virtual double volume() = 0;

         virtual ~Shape() {}
         
      //   virtual int bits() = 0;

};

class Cuboid:public Shape
{
    public:
      //   int bits()
      //  {
       //     return 0;
       // }
        void input(){
            cin>>c>>k>>g;
        }
        double area(){
            return 2*(c*k+c*g+k*g);
        }
        double volume(){
            return c*k*g;
        }
};

class Cylinder:public Shape
{
        public:
        void input(){
            cin>>x>>y;
        }
        int bits()
        {
            return 3;
        }
        double area(){
            return (2*pi*x*x+2*pi*x*y);
        }
        double volume(){
            return (pi*x*x*y);
        }
};

class Ball:public Shape
{
        
        public:
            int bits()
        {
            return 3;
        }
        void input(){
            cin>>x;
        }
        double area(){
            return x*x*4*pi;
        }
        double volume(){
            return 4.0/3.0*pi*x*x*x;
        }
};
void work(Shape *s) {
    //int bit;
    s->input();
  //  bit=s->bits();
   // cout << setiosflags(ios::fixed) << setprecision(bit);
    cout << s->area() << " " << s->volume() << endl;
    delete s;
}

int main() {

char c;

while (cin >> c) {

                   switch (c) {

                   case 'c': work(new Cuboid()); break;

                   case 'y': work(new Cylinder()); break;

                   case 'q': work(new Ball()); break;

                   default: break;

                   }

}

return 0;

}
View Code

....

Person和Student

发布时间: 2019年3月19日 10:35   时间限制: 1000ms   内存限制: 128M

实现一个Person类,再实现一个Student类(以Person类为基类),通过以下测试:

int main(){

Person * p;

p = new Person;

p->input();

p->display();

delete p;

p = new Student;

p->input();

p->display();

delete p;

return 0;

}

输入包含两行,第一行为一个姓名(不包含空格);第二行为一个学号和一个姓名(姓名不包含空格),学号和姓名之间用空格间隔

输出为两行,第一行为一个姓名;第二行为学号和姓名,学号和姓名之间用空格间隔

Mary
001 Mary
Mary
001 Mary

不能修改main函数,否则不得分。

....

#include <iostream>
#include <cstdio>

using namespace std;

class Person{
    protected:
        char name[21];
    
    public:
    virtual    void input();
    virtual    void display();
};
void Person::input(){
            cin>>name;
}
        
void Person::display()
{
            cout<<name<<endl;
}
class Student: public Person
{
    
    private:
        char num[21];
    public:
    virtual    void input();
    virtual    void display();
};
 void Student::input()
{
    scanf("%s%s",num,name);
//    cout<<"Student读入成功"<<num<<" "<<name<<endl;
}
void Student::display(){
    cout<<num<<" "<<name<<endl;
}
int main(){

Person * p;

p = new Person;

p->input();

p->display();

delete p;

p = new Student;

p->input();

p->display();

delete p;

return 0;

}
View Code

Vehicle类

发布时间: 2019年3月19日 10:56   最后更新: 2019年3月19日 10:57   时间限制: 1000ms   内存限制: 128M

设计一个抽象类Vehicle,由它派生出类Car和类Truck,类Car包含名称、颜色和载客数三个数据成员,类Truck包含名称、颜色和载重量三个数据成员。

使用如下函数测试你的程序:

int main() {

 Vehicle *p;

 char type;

 char name[110],color[110];

 int pas;

 double cap;

 while(cin>>type){

 cin>>name>>color;

if(type == 'C'){

cin>>pas;

Car car(name,color,pas);

p = &car;

p->display();

}else if(type == 'T'){

cin>>cap;

Truck truck(name,color,cap);

p = &truck;

p->display();

}

 }

 return 0;

}

多组输入,每组输入的开头是'C'或者'T',代表此时我们要输入的车的信息分别为Car和Truck.当输入的是

Car的时候,我们要输入它的名称,颜色和载客数;当输入的是Truck的时候,我们要输入它的名称,颜色和载重量。然后用抽象类的Vehicle的指针来指向派生类对象,从而实现不同类中display()函数的多态性。

根据不同车种类,输出不同信息,具体见样例输出。

C Benz black 3
T Dongfeng white 8.5
Car name:Benz Car color:black Car passager:3
Truck name:Dongfeng Truck color:white Truck capacity:8.5

Vehicle中可包含名称和颜色数据成员,并且有纯虚函数以提供接口完成信息的显示;在派生类Car和Truck中根据需要实现纯虚函数以及添加成员。

输出的时候不同项目之间用一个空格隔开。

。.

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <string.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <cctype>
#include <iomanip>
using namespace std;

class Vehicle{
    protected:
        char na[110];
        char co[110];
        int pa;
        double ca;
      public:
          virtual  void display()=0;
};


class Car :public Vehicle{
    protected:
        char na[110];
        char co[110];
        int pa;
        double ca;
    public:
        Car(char *name,char*color,int pas)
        {
            strcpy(na,name);
            strcpy(co,color);
            pa=pas;
        }
    virtual    void display()
        {
            cout<<"Car name:"<<na<<" Car color:"<<co<<" Car passager:"<<pa<<endl;
        }
        
};

class Truck :public Vehicle{
    protected:
        char na[110];
        char co[110];
        int pa;
        double ca;
    public:
        Truck(char *name,char*color,double cap)
        {
            strcpy(na,name);
            strcpy(co,color);
            ca=cap;
        }
        
    virtual    void display()
        {
            cout<<"Truck name:"<<na<<" Truck color:"<<co<<" Truck capacity:"<<ca<<endl;
        }
};
int main() {

 Vehicle *p;

 char type;

 char name[110],color[110];

 int pas;

 double cap;

 while(cin>>type){

 cin>>name>>color;

if(type == 'C'){

cin>>pas;

Car car(name,color,pas);

p = &car;

p->display();

}else if(type == 'T'){

cin>>cap;

Truck truck(name,color,cap);

p = &truck;

p->display();

}

 }

 return 0;

}
View Code

图书商品

发布时间: 2019年3月19日 11:00   最后更新: 2019年3月19日 11:02   时间限制: 1000ms   内存限制: 128M

编写两个类,分别是:

class Item_base{  //未打折的图书商品

protected:

    string ISBN;   //图书序列号

    double price;   //单价

public:

    Item_base(const string & book_ISBN = "", double sales_price = 0.0);

    string get_ISBN() const;

    virtual double net_price(int) const;  //返回购买指定数量的图书的总价

    virtual ~Item_base();

};

第二个类是:

class Bulk_Item : public Item_base{  //根据购买数量打折

public:

    Bulk_Item(const string & book_ISBN = "", double sales_price = 0.0, int min_qty = 0, double discount = 0.0);

    double net_price(int) const;  //返回根据购买数量打折后的总价

private:

    int min_qty;   // 买够这个数量可以打相应的折扣

    double discount;  //折扣

};

请实现以上两个类,使得以下的main函数成立

int main()

{

    Item_base book("0-001-0001-1", 10.0);

    Bulk_Item bulk1("0-001-0001-1",10.0, 5, 0.1);

    Bulk_Item bulk2("0-001-0001-1", 10.0, 10, 0.2);

   int num;

    while (cin >> num){

         cout << bulk1.get_ISBN() << " " << num << " ";

         Item_base * p;

        if (num >= 10) p = &bulk2;

        else if (num >= 5) p = &bulk1;

        else p = &book;

         cout << p->net_price(num) << " ";

    }

    return 0;

}

图书的数量。

输出购买的图书的ISBN,它的数量以及总的价格。(具体见main中输出的形式来输出即可)

2
6
11
0-001-0001-1     2     20
0-001-0001-1     6     54
0-001-0001-1     11    88

.

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <string.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <cctype>
#include <iomanip>
using namespace std;
class Item_base{  //未打折的图书商品

protected:

    string ISBN;   //图书序列号

    double price;   //单价

public:

    Item_base(const string & book_ISBN = "", double sales_price = 0.0){
        ISBN=book_ISBN;
        price=sales_price;
    }

    string get_ISBN() const{
        return ISBN;
    }

    virtual double net_price(int x) const{
        //    cout<<"小于5的折扣"<<endl; 
        //        cout<<"single:"<<price<<"number"<<x<<endl; 
        return price*x;
    }  //返回购买指定数量的图书的总价

    virtual ~Item_base(){
    };

};

//第二个类是:

class Bulk_Item : public Item_base{  //根据购买数量打折

    protected:
        double sales_pr;
        double minqty;
        double dis;
public:
    string get_ISBN() const{
        return ISBN;
    }
    Bulk_Item(const string & book_ISBN = "", double sales_price = 0.0, int min_qty = 0, double discount = 0.0){
         ISBN=book_ISBN;
        sales_pr=sales_price;
        minqty=min_qty;
        dis=discount;
    }

    double net_price(int x) const{
    
        //    cout<<"大于"<<minqty<<"的折扣"<<dis<<endl; 
            return x*sales_pr*(1.0-dis);
        
        
    }  //返回根据购买数量打折后的总价

};

//请实现以上两个类,使得以下的main函数成立

int main()

{

    Item_base book("0-001-0001-1", 10.0);

    Bulk_Item bulk1("0-001-0001-1",10.0, 5, 0.1);

    Bulk_Item bulk2("0-001-0001-1", 10.0, 10, 0.2);

   int num;

    while (cin >> num){

         cout << bulk1.get_ISBN() << "	" << num << "	";

         Item_base * p;

        if (num >= 10) p = &bulk2;

        else if (num >= 5) p = &bulk1;

        else p = &book;

         cout << p->net_price(num) << "
";
//    printf("0-001-0001-1     2     20
0-001-0001-1     6     54
0-001-0001-1     11    88
");
    }

    return 0;

}
View Code

 //czh'code save

#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int isLeapYear(int year) {//判断是否是闰年 
    return ((year%4==0) && (year%100!=0)||year%400==0);
}
int yeard(int y){//返回该年的天数 
    if (isLeapYear(y)){
        return 366;
    }else{
        return 365;
    }
}
struct Date0{
    int year;
    int month;
    int day;
};
int monthx(int m1,int y1) {//返回该月的天数 
    int num;
    switch(m1) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            num=31;
            break;
        case 2:
            num=yeard(y1)-337;
            break;
        default:
            num = 30;
            break;
    }
    return num;
}
class Date {
    public:
        Date(int d = 0, int m = 0, int y = 0,int d1=1,int m1=1,int y1=1901) {
            day=d;
            month=m;
            year=y;
            default_date.day=d1;
            default_date.month=m1;
            default_date.year=y1;
        } //构造函数
        int get_day() const {
            return day;
        } // 返回day
        int get_month() const {
            return month;
        } //返回month
        int get_year() const {
            return year;
        } // 返回year
        void set_default(int a, int b, int c) {
            default_date.day=a;
            default_date.month=b;
            default_date.year=c;
        }
        //设置default_date
        int get_default_day() {
            return default_date.day;
        } //返回缺省day
        int get_default_month() {
            return default_date.month;
        } //返回缺省month
        int get_default_year() {
            return default_date.year;
        } //返回缺省year
        Date & add_year(int n) {
            year+=n;
            return *this;
        } //加n年
        Date & add_month(int n) {
            int remain=n;
            while(remain>0){
                month++;
                remain--;
                if(month==13){
                    month=1;
                    year++;
                }
            } 
            return *this;
        }//加n月,考虑超过12月
        Date & add_day(int n) {
            int remain=n;//还剩的天数
            //最后加天数 
            while(remain>0){
                day++;
                remain--;
                if(day==monthx(month,year)+1){//进位 
                    day=1;
                    month++;
                }
                if(month==13){//进位  
                    month=1;
                    year++; 
                }
            } 
            return *this;
        }//加n天,考虑进位月和年,考虑闰年
    private:
        int day, month, year;
        Date0 default_date; //初始化为 1901年1月1日
};
int main() {
    char type[101];
    int day,mon,year;
    int addday,addmon,addyear;
    Date d1(1,1,1901);
    while(cin>>type) {
        if(strcmp(type,"Date") == 0) {
            cin>>day>>mon>>year;
            Date mydate(day,mon,year);
            cin>>addday>>addmon>>addyear;
            mydate.add_day(addday).add_month(addmon).add_year(addyear);
            cout << mydate.get_day() << " " << mydate.get_month() << " " << mydate.get_year() << endl;
        } else if(strcmp(type,"defaultDate") == 0) {
            cout << d1.get_default_day() << " " << d1.get_default_month() << " " << d1.get_default_year() << endl;
        } else if(strcmp(type,"setdefaultDate") == 0) {
            cin>>day>>mon>>year;
            d1.set_default(day,mon,year);
            cout << d1.get_default_day() << " " << d1.get_default_month() << " " << d1.get_default_year() << endl;
        }
    }
    return 0;
}
View Code

有理数类

设计一个有理数类Rational,要求对运算符“+”“-”“”“/”和“+=”“-=”“=”“/=”进行重载,完成有理数的加减乘除以及加减乘除复合赋值运算;并且重载“<<”和“>>”操作符完成有理数的输入和输出。最后,重载“==”和“!=”比较两个有理数是否相等。

  1 int gcd(int a, int b)
  2 {
  3     int temp;
  4     temp = a = abs(a);
  5     b = abs(b);
  6     a = a < b ? b : a;
  7     b = temp < b ? temp : b;
  8     if(a%b!=0)
  9         return gcd(a%b,b);
 10     else
 11         return b; 
 12 }
 13 
 14 class Rational
 15 {
 16 private:
 17     int z;    //分子
 18     int m;    //分母
 19 public:
 20     Rational(int a = 0, int b = 1)//构造有理数分数,分子默认为0,分母默认为1
 21     {
 22         z = a;
 23         m = b;
 24     }
 25     friend Rational& yuefen(Rational& r) //约分函数对分数化简
 26     {
 27         int t;
 28         t = gcd(r.z, r.m);
 29         r.z = r.z / t;
 30         r.m = r.m / t;
 31         
 32         
 33         //同号
 34         if (r.z < 0 && r.m < 0)
 35         {
 36             r.z = abs(r.z);
 37             r.m = abs(r.m);
 38         }
 39         //异号
 40         else if (r.z > 0 && r.m < 0)
 41         {
 42             r.z = -r.z;
 43             r.m = -r.m;
 44         }
 45         
 46         return r;
 47     }
 48 
 49     friend Rational operator+(const Rational &r1, const Rational &r2)
 50     {
 51         Rational temp;
 52         temp.m = r1.m*r2.m;
 53         temp.z = r1.z*r2.m + r2.z*r1.m;
 54         return temp;
 55     }
 56     friend Rational operator-(const Rational &r1, const Rational &r2)
 57     {
 58         Rational temp;
 59         temp.m = r1.m*r2.m;
 60         temp.z = r1.z*r2.m - r2.z*r1.m;
 61         return temp;
 62     }
 63     friend Rational operator*(const Rational &r1, const Rational &r2)
 64     {
 65         Rational temp;
 66         temp.m = r1.m*r2.m;
 67         temp.z = r1.z*r2.z;
 68         return temp;
 69     }
 70     friend Rational operator/(const Rational &r1, const Rational &r2)
 71     {
 72         Rational temp;
 73         temp.m = r1.m*r2.z;
 74         temp.z = r1.z*r2.m;
 75         return temp;
 76     }
 77     Rational & operator+=(const Rational &r)
 78     {
 79         *this = *this + r;
 80         return *this;
 81     }
 82     Rational & operator-=(const Rational &r)
 83     {
 84         *this = *this - r;
 85         return *this;
 86     }
 87     Rational & operator*=(const Rational &r)
 88     {
 89         *this = *this * r;
 90         return *this;
 91     }
 92 
 93     Rational & operator/=(const Rational &r)
 94     {
 95         *this = *this / r;
 96         return *this;
 97     }
 98     friend bool operator==(const Rational &r1, const Rational &r2)//判断两个有理数是否相等
 99     {
100         int t;
101         int r1m,r1z,r2m,r2z;
102         t = gcd(r1.z, r1.m);
103         r1z= r1z / t;
104         r1m = r1m / t;
105         
106         t = gcd(r2.z, r2.m);
107         r2z = r2.z / t;
108         r2m = r2.m / t;
109         if (r1m == r2m&&r1z == r2z)
110             return true;
111         else
112             return false;
113     }
114     friend bool operator!=(const Rational &r1, const Rational &r2)//判断两个有理数是否不等
115     {
116         int t;
117         int r1m,r1z,r2m,r2z;
118         t = gcd(r1.z, r1.m);
119         r1z= r1z / t;
120         r1m = r1m / t;
121         
122         t = gcd(r2.z, r2.m);
123         r2z = r2.z / t;
124         r2m = r2.m / t;
125         
126         if (r1m == r2m&&r1z == r2z)
127             return false;
128         else
129             return true;
130     }
131     friend ostream & operator<<(ostream &os, const Rational &r)
132     {
133 
134         os<< r.z << "/" << r.m;
135         return os;
136     }
137 
138     friend istream & operator>>(istream &is, Rational &r)
139     {
140         is >> r.z >> r.m;
141         return is;
142     }
143 
144 };
View Code

main函数

 1 int main()
 2 
 3 {
 4 
 5 Rational r1, r2,r3;
 6 
 7 while(cin>>r1>>r2)
 8 
 9 {
10 
11 cout << "r1 = " << yuefen(r1) << "
" << "r2 = " << yuefen(r2) << endl;
12  r3 = r1 + r2;
13  cout << "r1+r2 = " << yuefen(r3) << endl;
14  r3 = r1 - r2;
15  cout << "r1-r2 = " << yuefen(r3) << endl;
16  r3 = r1 * r2;
17  cout << "r1*r2 = " << yuefen(r3) << endl;
18  r3 = r1 / r2;
19  cout << "r1/r2 = " << yuefen(r3) << endl;
20 
21  cout << (r1 == r2) << " " << (r1 != r2) << endl;
22 
23  cout << yuefen(r1 += r2) << endl;
24 
25  cout << yuefen(r1 -= r2) << endl;
26 
27  cout << yuefen(r1 *= r2) << endl;
28 
29  cout << yuefen(r1 /= r2) << endl;
30 
31  }
32 
33  return 0;
34 
35 }
View Code
CheckedPtr
 

描述

 

自增(++)和自减(--)操作符经常由诸如迭代器这样的类实现,这样的类提供类似于指针的行为访问序列中的元

素。例如,可以定义一个类,该类指向一个数组并为该数组中的元素提供访问检查。假设,有以下类,它将处

理int数组。

 

 1 int main()
 2 
 3 {
 4 
 5  int array[10] = {1,2,3,4,5,6,7,8,9,10};
 6 
 7  CheckedPtr cp(array, array+10);
 8 
 9  for(;cp.GetCurr()<cp.GetEnd();cp++)
10 
11   cout<<*cp.GetCurr()<<" ";
12 
13  cout<<endl;
14 
15  for(--cp;cp.GetCurr()>cp.GetBeg();cp--)
16 
17   cout<<*cp.GetCurr()<<" ";
18 
19   cout<<*cp.GetCurr()<<endl;
20 
21  return 0;
22 
23 }
24 
25 输入
26 
27 28 
29 
30 输出
31 
32 1 2 3 4 5 6 7 8 9 1010 9 8 7 6 5 4 3 2 1
33 
34 
35 输入样例 1 
36 
37 38 输出样例 1
39 
40 1 2 3 4 5 6 7 8 9 10 
41 10 9 8 7 6 5 4 3 2 1
View Code

 

 

 1 class CheckedPtr
 2 
 3 {
 4 
 5 public:
 6 
 7     CheckedPtr(int * b, int * e) : beg(b), end(e), curr(b)
 8     {
 9         
10     }
11 
12     CheckedPtr & operator ++()// prefix ++
13     {
14     //    if (curr == end)
15         //    throw out_of_range("increment past the end of CheckedPtr");
16         ++curr;
17         return *this;
18     }
19     CheckedPtr & operator --()// prefix --
20     {
21     //    if (curr == beg)
22         //    throw out_of_range("decrement past the beginning of CheckedPtr");
23         --curr;
24         return *this;
25 
26     }
27     CheckedPtr   operator ++(int)// postfix ++
28     {
29         CheckedPtr ret(*this);
30         ++*this;
31         return ret;
32 
33     }
34     CheckedPtr   operator --(int)// postfix --
35     {
36         CheckedPtr ret(*this);
37         --*this;
38 
39     }
40 
41     int * GetBeg()
42     {
43         return beg;
44     }
45 
46     int * GetEnd()
47     {
48         return end;
49     }
50 
51     int * GetCurr()
52     {
53         return curr;
54     }
55 
56 private:
57 
58     int * beg;  // pointer to beginning of the array
59 
60     int * end;  // one past the end of the array
61 
62     int * curr; // current position within the array
63 
64 };
View Code

String类 

使用以下的main函数进行测试:

int main()
{
  String s;
  s += "hello";
  cout<<s<<endl;
  String s1("String1");
  String s2("copy of ");
  s2 += "String1";
 cout << s1 << "
" << s2 << endl;
 String s3;
  cin >> s3;
  cout << s3 << endl;
  String s4("String4"), s5(s4);
  cout << (s5 == s4) << endl;
  cout << (s5 != s4) << endl;
 String s6("End of "), s7("my string.");
  s6 += s7;
 cout << s6 << endl;
  return 0;
}

输入 

s3的值 

输出

一连串String类的字符串

输入样例 1 

String3

输出样例 1

hello
String1
copy of String1
String3
1
0
End of my string.

..

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cmath>
 4 #include <stdio.h>
 5 #include <cstring>
 6 #include <string>
 7 #include <cstdlib>
 8 #include <queue>
 9 #include <stack>
10 #include <set>
11 #include <vector>
12 #include <map>
13 #include <list>
14 #include <ctime>
15 #include <stddef.h>
16 
17 #define MAX 100000 
18 typedef long long ll;
19 using namespace std;
20 class String
21 {
22 private:
23   char * s;
24 public:
25   String(){
26       s=new char[1000];
27   }
28   String(const char *x){
29       s=new char[strlen(x)+1];
30       strcpy(s,x);
31   }
32   String(const String &x){
33   s=new char[strlen(x.s)+1];
34       strcpy(s,x.s);
35 }
36   ~String(){
37       delete [] s;
38   }
39   String & operator=(const String &x)
40   {
41       s=new char[strlen(x.s)+1];
42     strcpy(s,x.s);
43     return *this;
44   }
45   String & operator=(const char *x)
46   {
47       return operator=(String(x));
48 //      s=new char[strlen(x.s)+1];
49 //    strcpy(s,x.s);
50   }
51   
52   String operator+(const char *x){
53           return String(s)+String(x);
54   }
55 
56   String operator+(const String &x){
57           return String(s)+x;
58   }
59   String & operator+=(const String &x){
60       char *ret = new char[strlen(s)+ strlen(x.s) + 1];
61     ret = this->s;
62     strcat(ret, x.s);
63     this->s = ret;
64     return *this;
65   }
66   String & operator+=(const char *x){
67     return operator+=(String(x));
68   }
69   
70   friend istream & operator>>(istream &is, String &x)
71   {
72       char buf[1024];
73     is >> buf;
74     if(is){         
75         strcpy(x.s,buf);
76     }
77     return is;
78   }
79   friend ostream & operator<<(ostream &os, const String &x)
80   {
81       return os<<x.s;
82   }
83   friend bool operator==(const String &x, const char *y)
84   {
85       return strcmp(x.s,y)==0;
86   }
87   friend bool operator==(const String &x, const String &y)
88   {
89           return strcmp(x.s,y.s)==0;
90   }
91  friend bool operator!=(const String &x, const char *y)
92  {
93      return strcmp(x.s,y)!=0;
94  }
95   friend bool operator!=(const String &x, const String &y)
96   {
97       return strcmp(x.s,y.s)!=0;
98   }
99 };
View Code

..

Swap
 

描述

 

设计一个函数模板Swap,实现任意数据类型的两个数据的交换,分别用int型、double型和char型的数据进行测试

main函数如下:

int main()

{

int a1, a2;

double b1, b2;

char c1 , c2 ;

cin>>a1>>a2;

cin>>b1>>b2;

cin>>c1>>c2;

Swap(a1,a2);

cout<<a1<<","<<a2<<endl;

Swap(b1,b2);

cout<<b1<<","<<b2<<endl;

Swap(c1,c2);

cout<<c1<<","<<c2<<endl;

return 0;

}

输入

 

输入有三行,第一行两个整数,第二行两个浮点数,第三行两个字符

输出

 

输出三组输入交换之后的结果,每组用逗号隔开

输入样例 1 

2 3
1.2 2.3
a b

输出样例 1

3,2
2.3,1.2
b,a
1 template <typename T>
2 T & Swap(T & a,T & b)
3 {
4     T t;
5     t=a;
6     a=b;
7     b=t;
8 }
View Code

..

排序
 

描述

 

用函数模板的方式实现对不同数据类型的数组中的数据进行输入、从小到大排序和输出。

使用如下主函数测试你的模板

int main()

{

int a1[4];

char a2[5];

double a3[6];

int type;

while (cin >> type)

{

switch (type)

{

case 0: input(a1); sort(a1); output(a1); break;

case 1: input(a2); sort(a2); output(a2); break;

case 2: input(a3); sort(a3); output(a3); break;

}

}

return 0;

}

输入

 

输入包含多组测试数据。每组数据为两行,第一行为一个整数type,表示数据类型(0、1、2分别表示int、char、double)。第二行为数组元素。

输出

 

对于每一组测试数据,将其排序后在一行内输出,每个元素后跟一个空格。

输入样例 1 

0 3 6 1 4
1 A B C B A
2 0 1.1 2.2 1.2 -1.0 3.2

输出样例 1

1 3 4 6 
A A B B C 
-1 0 1.1 1.2 2.2 3.2
 1 void input(T(&parm)[N])
 2 {
 3     for(size_t i=0;i<N;++i)
 4     {
 5         cin>>parm[i];
 6     }
 7 }
 8 template <class T,size_t N>
 9 void sort(T(&parm)[N]){
10     int i, j, temp;
11     for (j = 0; j < N - 1; j++)
12         for (i = 0; i < N - 1 - j; i++)
13         {
14             if(parm[i] > parm[i + 1])
15             {
16                 temp = parm[i];
17                 parm[i] = parm[i + 1];
18                 parm[i + 1] = temp;
19             }
20         }
21 }
22 template <class T,size_t N>
23 void output(T(&parm)[N])
24 {
25     for(size_t i=0;i<N;++i)
26     {
27         cout<<parm[i];
28         if(i!=N-1)
29             printf(" ");
30         else{
31             cout<<endl;
32         }
33     }
34 }
View Code

.

描述

 

设计一个单向链表的类模板,类模板的说明如下:

template <class T>
class List
{
private:
 T data;
 List * next;
 static List * tail;      //指向最后一个结点
 static List * head;      //指向头结点
public:
         List():next(NULL)                  //构造头结点
        {
              head = tail = this;
         }
 List(T newnode):data(newnode),next(NULL)    //构造新结点
 {}
 void append(T node);               //往后面添加结点
 bool insert(T node, T posnode);   //在结点posnode第一次出现的后面插入新结点node, 插入成功返回true,否则false
 void deleteNode(T node);          //删除结点,注意可能有多个值相同的结点需要删除
 void delList();                   //删除整个链表
 void dispList();                  //显示链表
};

你的任务是实现这个类模板中的成员函数,然后使用如下所示的main()函数测试你实现的类模板。

int main()
{
  List<int> list1;
 list1.append(1);
 list1.deleteNode(1);
 list1.append(2);
 list1.append(3);
 list1.append(4);
list1.insert(10,2);
 list1.append(5);
 list1.append(3);
 list1.append(3);
 list1.dispList();
 list1.deleteNode(3);
 list1.dispList();
 list1.delList();
 list1.dispList();
List<char> list2;
 list2.append('A');
 list2.append('B');
 list2.append('C');
 list2.append('D');
 list2.insert('E','B');
 list2.insert('F','D');
 list2.append('G');
 list2.append('G');
 list2.append('G');
 list2.dispList();
 list2.deleteNode('G');
list2.dispList();
 list2.delList();
 list2.dispList();
return 0;
}

输入

 

输出

 

2 10 3 4 5 3 32 10 4 5

A B E C D F G G GA B E C D F

输入样例 1 

输出样例 1

2 10 3 4 5 3 3
2 10 4 5

A B E C D F G G G
A B E C D F

提示

(1)append函数是在链表尾部(即tail指向的结点)后面增加一个新节点,因此tail指针有变化。

(2)在insert函数中,需要先找到posnode,因此要定义一个指针指向posnode;然后新建一个结点(该结点的数据是node);如果posnode是最后一个结点,插入新节点还需要修改tail指针,否则直插入新节点不需要修改tail指针。

(3)在deleteNode函数中,需要两个临时指针find,pre,其中find指向pre的next,最终find指向删除的结点。在循环中,如果需要删除的是最后一个节点,需要修改tail指针,删除find,然后find=NULL;如果不是最后一个结点,把find指向的结点从链表中分离出来,删除find,find指向pre的next;如果没有找到删除的结点,则继续找下一个结点:pre =find;find=find->next

(4)在delList函数中,从头循环将要删除的结点从链表中分离出来,头指针相应修改,然后删除(delete)分离的结点。最后将tail和head指向同一个,next指针为NULL。

(5)在dispList函数中,从头到尾显示结点。

  1 #include <iostream>
  2 #include <algorithm>
  3 #include <cmath>
  4 #include <stdio.h>
  5 #include <cstring>
  6 #include <string>
  7 #include <cstdlib>
  8 #include <queue>
  9 #include <stack>
 10 #include <set>
 11 #include <vector>
 12 //#include <map>
 13 //#include <list>
 14 //#include <ctime>
 15 #include <stddef.h>
 16 
 17 #define MAX 100000 
 18 typedef long long ll;
 19 using namespace std;
 20 
 21 template <class T>
 22 class List
 23 {
 24 private:
 25  T data;
 26  List * next;
 27  static List * tail;      //指向最后一个结点
 28  static List * head;      //指向头结点
 29 public:
 30          List():next(NULL)                  //构造头结点
 31         {
 32               head = tail = this;
 33          }
 34  List(T newnode):data(newnode),next(NULL)    //构造新结点
 35  {}
 36  void append(T node)              //往后面添加结点
 37  {
 38  //    tail->data=node->data;
 39      List *p=new List(node);
 40      tail->next=p;
 41     tail=p;
 42      
 43  }
 44  bool insert(T node, T posnode)  //在结点posnode第一次出现的后面插入新结点node, 插入成功返回true,否则false
 45  {
 46      List *f=head->next;
 47      
 48      for(;f!=NULL;f=f->next)
 49      {List *p=new List(node);
 50          if(f->data==posnode)
 51          {
 52              if(f->next==NULL)
 53              {
 54                  p->next=NULL;
 55                  f->next=tail=p;
 56                  return true;
 57              }
 58              else{
 59                  p->next=f->next;
 60                  f->next=p;
 61                  return true;
 62              }
 63          }
 64      }
 65  }
 66  void deleteNode(T node)         //删除结点,注意可能有多个值相同的结点需要删除
 67  {
 68      List *p=head;
 69      List *f=head->next;
 70      while(f!=NULL)
 71      {
 72          if(f->data==node)
 73          {
 74             if(f->next==NULL) 
 75             { //要删除的是最后一个结点,需要修改tail
 76                 p->next=NULL;
 77                 tail=p;
 78                 delete f;
 79                 f=NULL;
 80             }
 81             else 
 82             { //要删除的不是最后一个结点
 83                 p->next=f->next;
 84                 delete f;
 85                 f=p->next;
 86             }
 87         
 88          }
 89          else{
 90                 p=f;
 91                 f=f->next;
 92             }    
 93      }
 94  }
 95  void delList()             //删除整个链表
 96  {
 97      List *p=head;
 98      List *f=head->next;
 99      while(f!= NULL)
100     {
101         p->next=f->next;
102         delete f;
103         f= p->next;
104     }
105     tail=head;
106  }
107  void dispList()                 //显示链表
108  {
109      List *temp=head->next;
110      while(temp!=NULL)
111      {
112          cout<<temp->data<<" ";
113          temp=temp->next;
114      }
115      cout<<endl;
116      temp=NULL;
117  }
118 };
119 
120 template<class T>
121 List<T> * List<T>::head=NULL;
122 
123 template<class T>
124 List<T> * List<T>::tail=NULL;
View Code
Stack类模板
 

描述

 

实现一个Stack类模板并测试这一模板.

template<class T, int SIZE = 20>
class Stack
{
private: 
 T array[SIZE];       //数组,用于存放栈的元素
 int top;             //栈顶位置(数组下标)
public:
 Stack();               //构造函数,初始化栈
 void push(const T & ); //元素入栈
 T pop();               //栈顶元素出栈
 void clear();          //将栈清空
 const T & Top() const;  //访问栈顶元素
 bool empty() const;     //测试栈是否为空
 bool full() const;     //测试是否栈满
 int size();            //返回当前栈中元素个数
};

测试函数:

int main()
{
 Stack<int,10> intStack;
 for(int i=0;i<10;i++)
  intStack.push(i);
 if(intStack.full()) cout<<"Now, intStack is full."<<endl;
 for(int i=0;i<10;i++)
  cout<<intStack.Top()<<" ";
 cout<<endl;
 for(int i=0;i<10;i++)
  cout<<intStack.pop()<<" ";
 cout<<endl;
 if(intStack.empty()) cout<<"Now, intStack is empty."<<endl;
 Stack<string,5> stringStack;
 stringStack.push("One");
 stringStack.push("Two");
 stringStack.push("Three");
 stringStack.push("Four");
 stringStack.push("Five");
 cout<<"There are "<<stringStack.size()<<" elements in stringStack."<<endl;
 stringStack.clear();
 if(stringStack.empty()) cout<<"Now, there are no elements in stringStack"<<endl;
cout<<stringStack.Top()<<endl;
 return 0;
}

输入

 

输出

 

Now, intStack is full.9 9 9 9 9 9 9 9 9 9 9 8 7 6 5 4 3 2 1 0 Now, intStack is empty.There are 5 elements in stringStack.Now, there are no elements in stringStack

输入样例 1 

输出样例 1

Now, intStack is full.
9 9 9 9 9 9 9 9 9 9 
9 8 7 6 5 4 3 2 1 0 
Now, intStack is empty.
There are 5 elements in stringStack.
Now, there are no elements in stringStack

提示

(1)堆栈的操作是在栈顶进行,在这里堆栈就是个数组,top表示数组下标,array数组存放堆栈的元素(即内容)。

(2)构造函数是对堆栈进行初始化,因为没有形参,所以在这里将top赋值成-1,也就是堆栈为空。这里将top赋值成-1,表示如果top值为-1说明堆栈为空。(也可将top赋值成0,但是判断堆栈是否为空和入栈等相应函数内容有所改变)

(3)push函数是将元素入栈。在函数中首先判断堆栈是否满了,不满的话将元素入栈,因此需要修改array数组和top下标。

(4)pop函数是栈顶元素出栈。在函数中首先判断堆栈是否空了,不空的话将栈顶元素出栈(即返回栈顶的元素值,修改下标的值);否则退出(可用exit(0)语句)。

(5)clear函数清空堆栈,即将top重新赋值为-1。

(6)Top函数访问栈顶元素,如果堆栈不空,接将栈顶元素返回;否则退出(可用exit(0)语句)。

(7)empty函数测试栈是否为空,如果top==-1则空,否则不空。

(8)full函数测试是否栈满,如果top==SIZE-1则满,否则不满。

(9)size函数返回当前栈中元素个数,考虑类中哪个成员可以表示栈中元素个数?返回它的值即可。

.

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cmath>
 4 #include <stdio.h>
 5 #include <cstring>
 6 #include <string>
 7 #include <cstdlib>
 8 #include <queue>
 9 #include <stack>
10 #include <set>
11 #include <vector>
12 //#include <map>
13 //#include <list>
14 //#include <ctime>
15 #include <stddef.h>
16 
17 #define MAX 100000 
18 typedef long long ll;
19 using namespace std;
20 template<class T, int SIZE = 20>
21 class Stack
22 {
23 private: 
24  T array[SIZE];       //数组,用于存放栈的元素
25  int top;             //栈顶位置(数组下标)
26 public:
27  Stack():top(-1){}
28               //构造函数,初始化栈
29  void push(const T & x) //元素入栈
30  {
31      
32      top++;
33      array[top]=x;
34 //     cout<<"push top=="<<top<<endl;
35 
36  }
37  T pop()               //栈顶元素出栈
38  {
39  //    cout<<"pop top=="<<top<<endl;
40      if(empty())
41          exit(0);
42      return array[top--];//多了换行 
43      
44  }
45  void clear()         //将栈清空
46  {
47      while (!empty())
48       top--;
49     
50  }
51  const T & Top() const  //访问栈顶元素
52  {
53      if(empty())
54          exit(0);
55      return array[top];
56  }
57  bool empty() const    //测试栈是否为空
58  {
59      if(top==-1)
60          return 1;
61      else
62          return 0;
63  }
64  bool full() const     //测试是否栈满
65  {
66      if(SIZE-1==top)
67          return 1;
68      else
69          return 0;
70  }
71  int size()           //返回当前栈中元素个数
72  {
73      return top+1; 
74      
75  }
76 };
View Code

..

#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
//#include <map>
//#include <list>
//#include <ctime>
#include <stddef.h>

#define MAX 100000
typedef long long ll;
using namespace std;
template<class T, int SIZE = 20>
class Stack
{
private:
T array[SIZE]; //数组,用于存放栈的元素
int top; //栈顶位置(数组下标)
public:
Stack():top(-1){}
//构造函数,初始化栈
void push(const T & x) //元素入栈
{

top++;
array[top]=x;
// cout<<"push top=="<<top<<endl;

}
T pop() //栈顶元素出栈
{
// cout<<"pop top=="<<top<<endl;
if(empty())
exit(0);
return array[top--];//多了换行

}
void clear() //将栈清空
{
while (!empty())
top--;

}
const T & Top() const //访问栈顶元素
{
if(empty())
exit(0);
return array[top];
}
bool empty() const //测试栈是否为空
{
if(top==-1)
return 1;
else
return 0;
}
bool full() const //测试是否栈满
{
if(SIZE-1==top)
return 1;
else
return 0;
}
int size() //返回当前栈中元素个数
{
return top+1;

}
};

 1 #include <iostream>
 2 #include <fstream>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <stdio.h>
 6 #include <cstring>
 7 #include <string>
 8 #include <cstdlib>
 9 #include <queue>
10 #include <stack>
11 #include <set>
12 #include <vector>
13 using namespace std;
14 void FileTest() {
15     fstream r,w;
16     r.open("colors.txt",ios::in);
17     w.open("temp.txt",ios::out);
18     int cnt=0;
19     char temp[9999];
20     
21     while(r.getline(temp,sizeof(temp)))
22     {
23         w<<++cnt<<" "<<temp<<endl;
24     }
25     
26     r.close();
27     w.close();
28     
29     
30 }
View Code

..

文件处理练习二
 

描述

 

编写程序,统计一篇英文文章中英文单词的个数以及文章的总行数。(参考ftp上的colors.txt文件)

void FileTest() {
// 此处写处理文件的代码
return;
}
int main()
{
FileTest();
cout << "Hello C++" << endl;
return 0;
}

输入

 

输出

 

Hello C++

输入样例 1 

输出样例 1

Hello C++

.

 1 #include <iostream>
 2 #include <fstream>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <stdio.h>
 6 #include <cstring>
 7 #include <string>
 8 #include <cstdlib>
 9 #include <queue>
10 #include <stack>
11 #include <set>
12 #include <vector>
13 
14 //#include <map>
15 //#include <list>
16 //#include <ctime>
17 #include <stddef.h>
18 using namespace std;
19 
20 //编写程序,完成两个英文文件的拼接。(参考ftp上的colors1.txt和colors2.txt文件,把colors2.txt拼接在colors1.txt后面)
21 void FileTest() 
22 {
23     //int cnt=0;
24 //    char c[9999];
25     int words=0;
26     int lines=0;
27     ifstream w;
28     ifstream r1;
29 //    w.open("temp.txt",ios::out);
30     r1.open("colors1.txt");
31 
32 
33     char str[256];
34   while(r1.getline(str,256))
35   { 
36       words++;
37     for(int i = 0; i < strlen(str); i++)
38     {
39         if(str[i] == ' ')
40             words++;            //统计单词数
41   }
42     lines++;   //统计行数
43     
44    // 此处写处理文件的代码
45   
46 }
47 //cout<<"lines="<<lines<<"words="<<words<<endl;
48  return;
49 }
View Code
文件处理练习三
 

描述

 

编写程序,完成两个英文文件的拼接。(参考ftp上的colors1.txt和colors2.txt文件,把colors2.txt拼接在colors1.txt后面)

void FileTest() 
{
   // 此处写处理文件的代码
   return;
}
int main()
{
   FileTest();
   cout << "Hello C++" << endl;
   return 0;
}

输入

 

输出

 

Hello C++

输入样例 1 

输出样例 1

Hello C++
 1 #include <iostream>
 2 #include <fstream>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <stdio.h>
 6 #include <cstring>
 7 #include <string>
 8 #include <cstdlib>
 9 #include <queue>
10 #include <stack>
11 #include <set>
12 #include <vector>
13 
14 //#include <map>
15 //#include <list>
16 //#include <ctime>
17 #include <stddef.h>
18 using namespace std;
19 //编写程序,完成两个英文文件的拼接。(参考ftp上的colors1.txt和colors2.txt文件,把colors2.txt拼接在colors1.txt后面)
20 void FileTest() 
21 {
22     //int cnt=0;
23     char c[9999];
24 //    char c2[9999];
25 //    fstream w;
26     fstream r1;
27     fstream r2;
28 //    w.open("temp.txt",ios::out);
29     r1.open("colors1.txt",ios::out);
30     r2.open("colors2.txt",ios::in);
31 //    if(!r1)
32 //    {
33 //        //cout<<"Cannot open the c1 file.
";
34 //        exit(0);
35 //    }
36 //    if(!r2)
37 //    {
38 //        //cout<<"Cannot open the c2 file.
";
39 //        exit(0);
40 //    }
41 //    
42 //    while(r1.getline(c,sizeof(c)))
43 //    {
44 //        w<<c<<endl;
45 //    }
46 
47     while(r2.eof())
48     {
49         r2.getline(c,sizeof(c));
50         for(int i=0;i<9999;++i)
51         {
52             if(c[i]=='
')
53             {
54                 r1.put('
');
55                 break;
56             } 
57             
58             r1.put(c[i]);
59         }
60     //    r1.put(c[i]);
61     }
62         r1.close();
63         r2.close();
64     //    w.close();
65 //        while(w.getline(c,sizeof(c)))
66 //    {
67 //        
68 //        r2<<c<<endl;
69 //    }
70 //        r1.close();
71 //        r2.close();
72 //        w.close();
73 //        
74     
75    // 此处写处理文件的代码
76    return;
77 }
View Code

..

文件处理练习四
 

描述

 

从文件in.txt读入一个正整数n,然后读取n个正整数a1,a2,…,an,最后再读一个正整数m。统计a1,a2,…,an中有多少个整数的值小于m,把结果输出到文件out.txt中。要求:in.txt可包含多组数据,因此,out.txt也应该包含对应的多组输出结果。(参考ftp上的in.txt 和 out.txt 文件)

void FileTest() 
{
   // 此处写处理文件的代码
   return;
}
int main()
{
   FileTest();
   cout << "Hello C++" << endl;
   return 0;
}

输入

 

输出

 

Hello C++

输入样例 1 

输出样例 1

Hello C++
 1 #include <iostream>
 2 #include <fstream>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <stdio.h>
 6 #include <cstring>
 7 #include <string>
 8 #include <cstdlib>
 9 #include <queue>
10 #include <stack>
11 #include <set>
12 #include <vector>
13 
14 //#include <map>
15 //#include <list>
16 //#include <ctime>
17 #include <stddef.h>
18 using namespace std;
19 /*从文件in.txt读入一个正整数n,
20 然后读取n个正整数a1,a2,…,an,
21 最后再读一个正整数m。
22 统计a1,a2,…,an中有多少个整数的值小于m
23 ,把结果输出到文件out.txt中。
24 要求:in.txt可包含多组数据,因此,out.txt也应该包含对应的多组输出结果。*/
25 void FileTest() 
26 {
27     fstream f1,f2;
28     f1.open("in.txt",ios::in);
29     f2.open("out.txt",ios::out);
30     
31     char c[999],ch;
32     int cnt,n,m;
33     int a[999];
34     while(f1.eof())
35     {
36         f1.get(ch);
37         n=(int)ch-48;
38         for(int i=1;i<=n;++i)
39         {
40             f1.get(c[i]);
41             a[i]=(int)c[i]-48;
42         }
43         
44         f1.get(ch);
45         m=(int)ch-48;
46         cnt=0;
47         
48         for(int i=1;i<=n;++i)
49         {
50             if(a[i]<m)
51                 cnt++;
52         }
53         cnt=cnt+48; 
54         f2.put(cnt);
55         f2.put('
');
56     }
57    // 此处写处理文件的代码
58    f1.close();
59    f2.close();
60    return;
61 }
View Code

.

文件处理练习一
 

描述

 

编写程序,打开一个英文的文本文件,在其中每一行的前面加上行号和一个空格符。(参考ftp上的colors.txt文件)将你的代码填在下面的注释处,其他3道题类似。

void FileTest() {
// 此处写处理文件的代码
return;
}
int main()
{
FileTest();
cout << "Hello C++" << endl;
return 0;
}

输入

 

输出

 

Hello C++

输入样例 1 

输出样例 1

Hello C++

 1 #include <iostream>
 2 #include <fstream>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <stdio.h>
 6 #include <cstring>
 7 #include <string>
 8 #include <cstdlib>
 9 #include <queue>
10 #include <stack>
11 #include <set>
12 #include <vector>
13 using namespace std;
14 void FileTest() {
15     fstream r,w;
16     r.open("colors.txt",ios::in);
17     w.open("temp.txt",ios::out);
18     int cnt=0;
19     char temp[9999];
20     
21     while(r.getline(temp,sizeof(temp)))
22     {
23         w<<++cnt<<" "<<temp<<endl;
24     }
25     
26     r.close();
27     w.close();
28     
29     
30 }
View Code
字符排序
 

描述

 

编写程序,利用string类完成一个字符串中字符的排序(降序)并输出。

输入

 

输入仅一行,是一个仅由大小写字母和数字组成的字符串。

输出

 

输出排序后的字符串。

输入样例 1 

abcde

输出样例 1

edcba

#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <iomanip>
using namespace std;

bool cmp(char x,char y)
{
    return x>y;
}

int main()
{
    string s;
    cin>>s;
    char c[10000];
    strcpy(c,s.c_str());
    sort(c,c+s.length(),cmp);
    cout<<c;
    return 0;
}
View Code
字符串排序
 

描述

 

编写程序,利用vector容器输入若干个string类数据元素,将其排序后输出。

输入

 

输入的第一行是一个正整数N,表示接下来的字符串的个数。

输出

 

将输入的字符串(按字典序)排序后输出,每行一个。

输入样例 1 

4
C++
ACM
BJFU
Object

输出样例 1

ACM
BJFU
C++
Object

#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <iomanip>
using namespace std;

bool cmp(const string &x,const string &y)
{
    return x<y;
}

vector<string > v;
int main()
{
    int n;
    string s;
    cin>>n;
    v.clear();
    for(int i=0;i<n;++i)
    {
        cin>>s;
        v.push_back(s);
    }
    
    sort(v.begin(),v.end(),cmp); 
    for(int i=0;i<v.size();++i)
    {
        cout<<v[i]<<endl;
    }
    return 0;
}
View Code
list使用
 

描述

 

编写程序,定义一个结构体

struct Student{
 int no;
 string name;
};

并用这个结构体练习使用list。包含往list里添加元素以及输出list的所有元素。

输入

 

输入首先是一个整数n,表示共有n个学生信息,接下来n行,每行是一个整数和一个字符串,分别表示学生的学号和姓名。

输出

 

按顺序输出list中的所有元素,每个元素占一行。学号和姓名之间用一个空格分隔。

输入样例 1 

3
1010101 zhangsan
1010102 lisi
1010103 wangwu

输出样例 1

1010101 zhangsan
1010102 lisi
1010103 wangwu

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cmath>
 4 #include <stdio.h>
 5 #include <cstring>
 6 #include <string>
 7 #include <cstdlib>
 8 #include <queue>
 9 #include <stack>
10 #include <set>
11 #include <vector>
12 #include <map>
13 #include <list>
14 #include <iomanip>
15 using namespace std;
16 
17 struct Student{
18  int no;
19  string name;
20 };
21 list<Student> l;
22 
23 int main()
24 {
25     int n;
26     cin>>n;
27     while (n--)
28     {
29         Student stu;
30         cin>>stu.no>>stu.name;
31         l.push_back(stu);
32     }
33     list<Student>::iterator it;
34     for(it=l.begin();it!=l.end();it++)
35     {
36         cout<<(*it).no<<" "<<(*it).name<<endl;
37     
38     }
39     return 0;
40 }
View Code
卡片游戏
 

描述

 

桌上有一叠牌,从第一张牌(即位于顶面的牌)开始从上往下依次编号为1~n。当至少还剩两张牌时进行以下操作:把第一张牌扔掉,然后把新的第一张放到整叠牌的最后。请模拟这个过程,依次输出每次扔掉的牌以及最后剩下的牌的编号。

输入

 

输入仅一个正整数n(n<1000000)。

输出

 

在一行内依次输出每次扔掉的牌以及最后剩下的牌的编号,每个编号后跟一个空格。(所有输出最后加一个换行符)

输入样例 1 

7

输出样例 1

1 3 5 7 4 2 6

提示

 
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <iomanip>
using namespace std;

int main()
{
    int n;
    cin>>n;
    queue<int > q;
    for(int i=1;i<=n;++i)
    {
        q.push(i);
    }
    int num=n;
    while(num>=2)
    {
        //扔掉第一张牌 
        cout<<q.front()<<" ";
        q.pop(); 
        //牌的数量 -1 
        num--;
        //把新的第一张牌放到最后
        int newx=q.front();
        q.pop();
        q.push(newx);
    }
    
    cout<<q.front()<<endl; 
    return 0;
}
View Code
大理石在哪儿
 

描述

 

现有N个大理石,每个大理石上写了一个非负整数。首先把各数从小到大排序,然后回答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,就回答哪个大理石上写着x(如果有多个大理石上出现x,那么回答第一次出现的大理石编号)。排序后的大理石从左到右编号为1~N。

输入

 

输入包含多组测试数据,每组数据分三行,第一行是两个正整数N(N<1000)和Q(Q<1000),第二行是N个非负整数,第三行是Q个非负整数。

输出

 

对于每一个询问(x),如果有第i个大理石上写着x,则输出x found at i,否则输出x not found。格式详见样例。

输入样例 1 

4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3

输出样例 1

5 found at 4
2 not found
3 found at 3

提示

 
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cmath>
 4 #include <stdio.h>
 5 #include <cstring>
 6 #include <string>
 7 #include <cstdlib>
 8 #include <queue>
 9 #include <stack>
10 #include <set>
11 #include <vector>
12 #include <map>
13 #include <list>
14 #include <iomanip>
15 using namespace std;
16 
17 bool cmp(int x,int y)
18 {
19     return x<y;
20 }
21 int main()
22 {
23     int n,q;
24     while(scanf("%d%d",&n,&q)!=EOF)
25     {
26         int a[1005];
27         for(int i=0;i<n;++i)
28         {
29             cin>>a[i];
30         }
31         sort(a,a+n,cmp);
32 //        for(int i=0;i<n;++i)
33 ////        {
34 ////            cout<<"a"<<i<<"="<<a[i]<<" ";
35 ////        }
36 //        cout<<endl;
37         while(q--)
38         {
39             int quest,local;
40             cin>>quest;
41             local=lower_bound(a,a+n,quest)-a+1;
42             if(a[local-1]!=quest)
43                 cout<<quest<<" not found"<<endl;
44             else
45                 cout<<quest<<" found at "<<local<<endl;
46         }
47     }
48     return 0; 
49 } 
View Code
 
铁轨(选做)
 

描述

 

某城市有一个火车站,铁轨铺设如图所示。有n节车厢从A方向驶入车站,按进站顺序编号为1~n.你的任务是让它们按照某种特定的顺序进入B方向的铁轨并驶出车站。为了重组车厢,你可以借助中转站C。这是一个可以停放任意多节车厢的车站,但由于末端封顶,驶入C的车厢必须按照相反的顺序驶出C。对于每个车厢,一旦从A移入C,就不能再回到A了;一旦从C移入B,就不能回到C了。换句话说,在任一时刻,只有两种选择:A->C和C->B。

ffd15b0ac3afe2fda2a10bc60fabfbf8.blob.png

输入

 

输入包含多组测试数据,每组数据的第一行是一个正整数n(1<n<1000),第二行是1~n这n个整数的一个全排列。

输出

 

对于每一组测试数据,如果能按要求完成车厢重组,请输出“Yes”,否则输出“No”,每组输出占一行。

输入样例 1 

5
1 2 3 4 5
5
5 4 1 2 3
6
6 5 4 3 2 1

输出样例 1

Yes
No
Yes

提示

 
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <iomanip>
//#include <>
using namespace std;
const int maxn=1005;
int n,rail[maxn];
int main()
{
    while(scanf("%d",&n)==1)
    {
        stack<int > s;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&rail[i]);
        }
        int flag,a,b;
        a=b=flag=1;
        while(b<=n)
        {
            if(a==rail[b])
            {
                a++;
                b++;
            }
            else if(!s.empty()&&s.top()==rail[b])
            {
                s.pop();
                b++;
            }
            else if(a<=n)//top最大值是n-1
                s.push(a++);
            else
            {
                flag=0;
                break;
            }
        }
        printf("%s
",flag?"Yes":"No");
    }
    return 0;
}
View Code
丑数(选做)
 

描述

 

丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排列起来,结果如下:

1,2,3,4,5,6,8,9,10,12,15,…

输入

 

输入有多组,每组输入一个n(n<=10000)

输出

 

输出第n个丑数,以换行结尾。

输入样例 1 

1500

输出样例 1

859963392

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cmath>
 4 #include <stdio.h>
 5 #include <cstring>
 6 #include <string>
 7 #include <cstdlib>
 8 #include <queue>
 9 #include <stack>
10 #include <set>
11 #include <vector>
12 #include <map>
13 #include <list>
14 #include <iomanip>
15 using namespace std;
16 int cmp(int a, int b, int c)     
17 {     
18     int temp = (a < b ? a : b);     
19     return (temp < c ? temp : c);     
20 }     
21 int find(int n) //  
22 {     
23     int* ugly = new int[n];     
24     ugly[0] = 1;     
25     int index2 = 0;     
26     int index3 = 0;     
27     int index5 = 0;     
28     int index = 1;     
29     while (index < n)     
30     {     
31         int val = cmp(ugly[index2]*2, ugly[index3]*3, ugly[index5]*5); 
32         if (val == ugly[index2]*2)    
33             ++index2;     
34         if (val == ugly[index3]*3)   
35             ++index3;     
36         if (val == ugly[index5]*5)     
37             ++index5;     
38         ugly[index++] = val;     
39     }     
40 
41     int result = ugly[n-1];     
42 //    delete[] ugly;     
43     return result;     
44 }     
45 int main()     
46 {     
47     int num;  
48     cin >> num;  
49     cout << find(num) << endl;  
50     return 0;     
51 }  
View Code
InputOutput
 

描述

 

设计一个保存你个人信息的类,包含姓名和年龄。并使用以下代码测试

int main()
{
    string    name;
    int    year;
    cin >> name >> year;
    PersonInfo info(name, year);
    cout << "I am " << info.Name() << ", " << info.Age() << " years old.
";
    return 0;
}

输入

 

姓名年龄

输出

 

见样例输出

输入样例 1 

master
999

输出样例 1

I am master, 999 years old.

提示

  1. 修改main函数会扣分
  2. 不使用类,没有分数
  3. ","后面有一个空格,"."结束,没有其它格式输出
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <iomanip>
using namespace std;
class PersonInfo{
    
    public:    string name;
        int year;
        PersonInfo(string& n,int y){
            name=n;
            year=y;
        }
        string Name()
        {
            return name;
        }
        int Age(){
            return year;
        }
};
View Code

Composite

描述

 

计算机包含CPU和硬盘。请设计Computer、CPU、Disk类。并满足以下测试

int main()
{
    string    cpuType, diskType;
    double    frequency, mount;
    cin >> cpuType >> frequency >> diskType >> mount;
    CPU cpu(cpuType, frequency);
    Disk disk(diskType, mount);
    Computer computer(cpu, disk);

    computer.Print();
    return 0;
}

输入

 

cpu类型 cpu主频disk类型 disk容量

输出

 

见样例

输入样例 1 

i7 2.9
ST 2

输出样例 1

The computer has a cpu and a disk.
CPU type: i7, CPU frequency: 2.9 GHz
disk type: ST, disk mount: 2 T
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <map>
#include <list>
#include <iomanip>
using namespace std;
class CPU{
    protected:
    string types;
    double count;
    public:
        CPU(string& t,double c)
        {
            types=t;
            count=c;
        }
        string typ()
        {
            return types;
        }
        double fre()
        {
            return count;
        }
};

class Disk{
        protected:
    string types;
    double count;
    public:
        Disk(string& t,double c)
        {
            types=t;
            count=c;
        }
        string typ()
        {
            return types;
        }
        double fre()
        {
            return count;
        }
};
class Computer{
    protected:
    string t1,t2;
    double c1,c2;
    public:
        Computer(CPU c,Disk d)
        {
            t1=c.typ();
            t2=d.typ();
            c1=c.fre();
            c2=d.fre();
        }
        void Print(){
            cout<<"The computer has a cpu and a disk.
CPU type: "<<t1<<", CPU frequency: "<<c1<<" GHz
disk type: "<<t2<<", disk mount: "<<c2<<" T"<<endl;    
        }
};
View Code
Inheritance
 

描述

 

不同的动物既有共性也有个性。鸟类会飞,鱼会游泳。请设计一个类层次结构表示。并通过以下测试

int main()
{
    Animal *animal;
    string    type, color;
    bool Osteichthyes, daytime;
    cin >> type >> color >> Osteichthyes;
    Fish fish(type, color, Osteichthyes);
    fish.Print();
    animal = &fish;
    animal->Print();
    cin >> type >> color >> daytime;
    Bird bird(type, color, daytime);
    bird.Print();
    animal = &bird;
    animal->Print();
    return 0;
}

输入

 

鱼类型 鱼的颜色 是否硬骨鸟类型 鸟的颜色 是否白天活动

输出

 

见样例,冒号和逗号后面各有一个空格

输入样例 1 

chub white 1
swallow black 1

输出样例 1

type: chub, color: white, Osteichthyes: 1
type: chub, color: white
type: swallow, color: black, daytime: 1
type: swallow, color: black
 1 class Animal{
 2     public:
 3         string type,color;
 4         bool yes;
 5         void Print(){
 6             cout<<"type: "<<this->type<<", color: "<<this->color<<endl;
 7         }
 8 };
 9 
10 class Fish:public Animal{
11     public:
12         Fish(string t,string c,bool y)
13         {
14             type=t;
15             color=c;
16             yes=y;
17         }
18      void Print(){
19         cout<<"type: "<<type<<", color: "<<color<<", Osteichthyes: "<<yes<<endl;
20     }
21     int yes;
22 };
23 
24 class Bird:public Animal{
25     public:
26         Bird(string t,string c,bool y)
27         {
28             type=t;
29             color=c;
30             yes=y;
31         }
32     void Print(){
33         cout<<"type: "<<type<<", color: "<<color<<", daytime: "<<yes<<endl;
34     }
35     int yes;
36 };
View Code
AdvancedInheritance
 

描述

 

不同的动物既有共性也有个性。鸟类会飞,鱼会游泳。请设计一个类层次结构表示。并通过以下测试

int main()
{
    Animal *animal;
    string    type, color;
    bool Osteichthyes, daytime;
    cin >> type >> color >> Osteichthyes;
    Fish fish(type, color, Osteichthyes);
    fish.Print();
    animal = &fish;
    animal->Print();
    cin >> type >> color >> daytime;
    Bird bird(type, color, daytime);
    bird.Print();
    animal = &bird;
    animal->Print();
    return 0;
}

输入

 

鱼类型 鱼的颜色 是否硬骨鸟类型 鸟的颜色 是否白天活动

输出

 

见样例,冒号和逗号后有一个空格

输入样例 1 

chub white 1
swallow black 1

输出样例 1

type: chub, color: white, Osteichthyes: 1
type: chub, color: white, Osteichthyes: 1
type: swallow, color: black, daytime: 1
type: swallow, color: black, daytime: 1
class Animal{
    public:
        string type,color;
        bool yes;
        virtual void Print(){    }
};

class Fish:public Animal{
    public:
        Fish(string t,string c,bool y)
        {
            type=t;
            color=c;
            yes=y;
        }
    virtual void Print(){
        cout<<"type: "<<type<<", color: "<<color<<", Osteichthyes: "<<yes<<endl;
    }
    int yes;
};

class Bird:public Animal{
    public:
        Bird(string t,string c,bool y)
        {
            type=t;
            color=c;
            yes=y;
        }
    virtual void Print(){
        cout<<"type: "<<type<<", color: "<<color<<", daytime: "<<yes<<endl;
    }
    int yes;
};
View Code
静态成员
 

描述

 

编写程序,统计某旅馆住宿客人的总数。要求输入客人的姓名,输出客人的编号(按先后顺序自动生成)、姓名使用如下main函数对程序进行测试

int main()
{
    int n;
    cin >> n;
    cin.get();
    Hotel *h = new Hotel[n+1];
    string name;
    for (int i = 0; i < n; i++)
    {
        GetName(name);
        h[i].SetName(name);
    }
    h[n].SetName("YOU");
     while (GetName(name))
    {
        bool bFound = false;
        for (int i = 0; i < Hotel::GetTotal(); i++)
        {
            if (h[i].GetName() == name)
            {
                 cout << name << " found! ";
                h[i].Print();
                bFound = true;
                break;
            }
        }
          if (!bFound)
            cout << name << " Not found!
";
    }
    return 0;
}

其中GetName是输入带空格姓名的函数。

输入

 

第一行为人数n后面n行,n个代表姓名的字符串后面要查询的名字

输出

 

参考样例

输入样例 1 

3
ONE
TWO
THREE
TWO
TWOO

输出样例 1

TWO found! id: 1, name: TWO
TWOO Not found!

class Hotel{
    private:
        string name;
        int id;
    public:
        static int count;
        Hotel(){
            id=count;
            count++;
        }
        void SetName(string n);
        string GetName();
        static int GetTotal(); 
        void Print();
};
void Hotel::SetName(string n)
{
    name=n;
}
int Hotel::GetTotal()
{
//    cout<<"count is"<<endl;
    return count;
}
int Hotel::count=0;
string Hotel::GetName()
{
//    cout<<"name is"<<endl;
    return name;
}


bool GetName(string &n)
{
//    cout<<"got name"<<endl;
    if(getline(cin,n))    
        return true;
    else
        return false;
}
void Hotel::Print()
{
    cout<<"id: "<<id<<", name: "<<name<<endl;
}
View Code
文件流
 

描述

 

in.txt是一个文本文件,保存了一些小数。文件第一行是小数个数m,后面一共m行小数。请读入这些数据,求出平均数,并保存到out.txt中。请用C++的文件流实现这个功能,并将代码放置到FileTest()中。注意本题要求:1.OJ测试通过。2.不修改代码,本地附带数据运行时能得到正确结果。

int main()
{
    FileTest();
    cout << "Hello C++
";
    return 0;
}

输入

 

输出

 

Hello C++

输入样例 1 

输出样例 1

Hello C++
void FileTest()
{
    ofstream w;
    ifstream r;
    r.open("in.txt",ios::in);
    w.open("out.txt",ios::out);
    
    double num[99];
    int m,i;
    double sum=0;
    r>>m;
    for(int i=0;i<m;++i)
    {
        r>>num[i];
        sum+=num[i];
    }
    sum/=m;
    w<<sum;
    r.close();
    w.close();
}
View Code
运算符重载
 

描述

 

描述:定义一个矩形类Rect,该类中有两个数据成员:整型的长和宽,要求重载“+”、“-”、“*”和“/”4个运算符分别实现矩形面积的和、差、积和商,重载“>>”,“<<”支持cin和cout。实现Rect类,并用以下主函数进行测试:

、、、

int main()

{

Rect r1(4,5),r2(2,1),r3,r4;
cin>>r3;
cin>>r4;
cout<<r1<<endl;
cout<<r2<<endl;
cout<<r3<<endl;
cout<<r4<<endl;
cout<<"r1+r2="<<r1+r2<<endl;
cout<<"r1-r2="<<r1-r2<<endl;
cout<<"r3*r4="<<r3*r4<<endl;
cout<<"r3/r4="<<r3/r4<<endl;
return 0;

}

、、、

输入

 

输入两个矩形的长和宽

输出

 

输出4个矩形的长和宽以及这4个矩形的面积和、差、积和商。长和宽之间用空格分割。

输入样例 1 

1 2
3 4

输出样例 1

4 5
2 1
1 2
3 4
r1+r2=22
r1-r2=18
r3*r4=24
r3/r4=0.166667
 1 class Rect{
 2     private:
 3         int h;
 4         int w;
 5     public:
 6         Rect(int x=0,int y=0){
 7             h=x;
 8             w=y;
 9         }
10         
11         friend int operator+(Rect &r1,Rect&r2) 
12         {
13             return r1.h*r1.w+r2.h*r2.w;
14         } 
15         friend int operator-(Rect &r1,Rect&r2) 
16         {
17             return r1.h*r1.w-r2.h*r2.w;
18         }     
19         friend int operator*(Rect &r1,Rect&r2) 
20         {
21             return r1.h*r1.w*r2.h*r2.w;
22         }     
23         friend double operator/(Rect &r1,Rect&r2) 
24         {
25             return (double)r1.h*r1.w/r2.h/r2.w;
26         } 
27         
28         friend istream& operator>>(istream& is,Rect &r)
29         {
30             is>>r.h>>r.w;
31             return is;
32         }
33         friend ostream& operator<<(ostream& os,Rect r)
34         {
35             os<<r.h<<" "<<r.w;
36             return os;
37         }
38 };
View Code
模板
 

描述

 

用函数模板的方式实现对不同数据类型的数组中的数据进行输入、输出最小值。使用如下主函数测试你的模板

、、、

int main()

{

int i;
int a1[4];
double a2[5];
string a3[6];
input<int>(a1,4);
input<double>(a2,5);
input<string>(a3,6);

cout<<"min of int is:"<<min<int>(a1,4)<<endl;
cout<<"min of double is:"<<min<double>(a2,5)<<endl;
cout<<"min of string is:"<<min<string>(a3,6)<<endl;
return 0;

}

输入

 

输入3行,第一行是4个int型数据,第二行是5个double型数据,第三行是6个string型数据

输出

 

输出3行,分别是输入3个输入数组的最小值

输入样例 1 

4 -6 8 1
-2.5 98.9 -2.3 -4.5 34.6
i love c++ how about you

输出样例 1

min of int is:-6
min of double is:-4.5
min of string is:about
template <typename T>
void input(T a[],int l)
{
    for(size_t i=0;i<l;++i)
    {
        cin>>a[i];
    }
}
template <typename T>
T min(T a[],int l)
{
    sort(a,a+l);
    return a[0];
}
View Code

..

..

STL
 

描述

 

要求编写函数模板,分别利用vector容器输入若干个string类数据元素和若干个double型数据元素,分别将其排序后输出。main函数如下:


int main()
{
    vector<string> s;
    insortout(s);
    vector<double> v;
    insortout(v);
    return 0;
}

输入

 

输入的第一行是一个正整数N,表示接下来的字符串的个数。再输入N个字符串再输入一个正整数M,表示接下来的double型数据的个数。再输入M个double型数据

输出

 

将输入的字符串(按字典序)排序后输出,每行一个。再将输入的double型数据从小到大排序输出,每行一个。

输入样例 1 

4
C++
ACM
BJFU
Object
4
0.3
-2.3
8
9

输出样例 1

ACM
BJFU
C++
Object
-2.3
0.3
8
9

、、、

template<class T>
void insortout(vector<T> vec)
{
      T str;
    int n;
    cin>>n;
    for(int i=0;i<n;++i)
    {
        cin>>str;
        vec.push_back(str);
    } 
    sort(vec.begin(),vec.end());
    for( auto it=vec.begin();it!=vec.end();it++)
        cout<<*it<<endl;
}
View Code
Singer类
 

描述

 

实现一个Singer类,通过以下测试:

int main()
{

Singer s1,s2;
cin>>s1>>s2;
cout<<s1<<"
"<<s2<<endl;

if(s1>s2)
cout<<s1.getName()<<"'s score is higher than "<<s2.getName()<<"'s.
";
else if(s1==s2)
cout<<s1.getName()<<"'s score is equal to "<<s2.getName()<<"'s.
";
else
cout<<s1.getName()<<"'s score is lower than "<<s2.getName()<<"'s.
";

return 0;
}

输入

 

输入包含两行,第一行为歌手s1的信息,第二行为歌手s2的信息,每位歌手的信息包括姓名(不包含空格)、性别、年龄 和 分数;姓名、性别、年龄和分数之间用空格分隔

输出

 

输出为三行,前两行分别是歌手s1和s2的信息,第三行根据s1和s2比较结果输出(s1和s2的比较结果和他们的分数的比较结果一致),具体参见主函数

输入样例 1 

Mary F 28 99.5
Peter M 26 98

输出样例 1

Mary F 28 99.5
Peter M 26 98
Mary's score is higher than Peter's.
 1 class Singer{
 2     private:
 3         string name;
 4         char sex;
 5         int age;
 6         double score;
 7     public:
 8         Singer(){}
 9         string getName(){
10             return name;
11         }
12         friend bool operator >(Singer x,Singer y)
13         {
14             if(x.score>y.score)
15                 return true;
16             else
17                 return false;
18         }
19         friend bool operator ==(Singer x,Singer y)
20         {
21             if(x.score==y.score)
22                 return true;
23             else
24                 return false;
25         }
26         friend istream& operator>>(istream& is,Singer &s)
27         {
28             is>>s.name>>s.sex>>s.age>>s.score;
29             return is;
30         }
31         friend ostream& operator<<(ostream& os,Singer s)
32         {
33             os<<s.name<<" "<<s.sex<<" "<<s.age<<" "<<s.score;
34             return os;
35         }
36 };
View Code
Search
 

描述

 

设计一个函数模板,实现在一个给定的数组中查找给定的元素的值是否存在,如果存在则输出该元素在数组中最小的下标,如果不存在,输出-1。

输入

 

输入共三组数据,每组数据占两行。第一组数据的第一行为一个整数n1和d,第二行是n1个整数。第二组数据的第一行为一个整数n2和一个浮点数f,第二行是n2个浮点数。第三组数据的第一行为一个整数n3和一个字符c,第二行是n3个字符。

输出

 

对于每一组输入,如果给定元素存在,则输出其最小下标(下标从0开始计),否则输出-1。

输入样例 1 

7 8
1 1 2 5 8 10 13
5 3.5
-1.0 1.1 1.2 1000.10101 8.9
4 j
B J F U

输出样例 1

4
-1
-1
 1 int n,x1,a1[103];
 2 float x2,a2[103];
 3 char x3,a3[103];
 4 template<class T,size_t N>
 5 int input(T(&parm)[N],T x)
 6 {
 7     int flag=0,ans=-1;
 8     for(int i=0;i<n;++i)
 9     {
10         cin>>parm[i];
11         if(parm[i]==x)
12             {
13                 flag=1;
14                 ans=i;
15             //    cout<<"parm[i]="<<parm[i]<<"x"<<x<<endl;
16             }
17     }
18     return ans;
19 }
20 int main()
21 {
22     int re;
23     cin>>n>>x1;
24     re=input(a1,x1);
25     cout<<re<<endl;
26     
27     cin>>n>>x2;
28     re=input(a2,x2);
29     cout<<re<<endl;
30     
31     cin>>n>>x3;
32     re=input(a3,x3);
33     cout<<re<<endl;
34     
35 }
View Code
Person类
 

描述

 

编写程序实现Person类,Student类和Teacher类。Person类如下所示:

class Person
{
protected:
           string name;
           int age;
public:
           Person();
           virtual ~Person();
           virtual void input();
           virtual void show();
};

使用Person类派生出Student类(增加“学号”数据成员)和Teacher类(增加“职称”数据成员),在这些类里分别实现继承的虚函数。使用如下代码测试运行。

void work(Person *p) {
           p->input();
           p->show();
           delete p;
}
int main() {
           char c;
           while (cin >> c) {
                     switch (c) {
                     case 'p':
                                work(new Person());
                                break;
                     case 's':
                                work(new Student());
                                break;
                    case 't':
                                work(new Teacher());
                                break;
                     default:
                                break;
                     }
           }
           return 0;
}

输入

 

输入包含多行,每行首先是一个字符’p’,’s’,’t’(三者中一个),分别表示输入Person、Student或Teacher的信息,接下来是对应的输入。

输出

 

每行输入对应一行输出,输出该对象的信息(以空格间隔)

输入样例 1 

p Mary 18
s Tom 20 10001
t John 30 Professor

输出样例 1

Mary 18
Tom 20 10001
John 30 Professor
class Person
{
protected:
           string name;
           int age;
public:
           Person(){}
           virtual ~Person(){}
           virtual void input();
           virtual void show();
};

void Person::input()
{
    cin>>name>>age;
}

void Person::show()
{
    cout<<name<<" "<<age<<endl;
}
class Student:public Person{
    public:
        int xuehao;
    virtual void input()
    {
        cin>>name>>age>>xuehao;
    }
    
    virtual void show()
    {
        cout<<name<<" "<<age<<" "<<xuehao<<endl;    
    }
};
class Teacher:public Person{
    public:
        string level;
     virtual void input()
    {
        cin>>name>>age>>level;
    }
    virtual void show()
    {
        cout<<name<<" "<<age<<" "<<level<<endl;    
    }
};
void work(Person *p) {
           p->input();
           p->show();
           delete p;
}
View Code
图书排序
 

描述

 

以下是图书类Book的声明,缺少实现部分

class Book {
private:
    char name[102];
    char author[102];
    int sale;
public:
    Book();
    Book(const char *a, const char *b, int c);
    void print();
    void input();
    friend bool operator<(const Book&, const Book&);
    ~Book();
};

请予以实现,并能对图书进行排序(先按销量从大到小排,销量相同则按书名的字典序排,书名相同则按作者的字典序排)。使用如下main函数测试你的程序:

int main() {
           int N;
           cin >> N;
           Book *books = new Book[N];
           for(int i = 0; i < N; i++) {
                     books[i].input();
           }
           sort(books, books + N);
           for(int i = 0; i < N; i++) {
                     books[i].print();
           }
           delete[] books;
           return 0;
}

输入

 

输入的第一行为一个整数N(0<N<50),表示图书的数量。然后是N行,每行一条图书信息,分别为”书名”、”作者”、”销售量”。”书名”和”作者”均只由大小写字母或_组成,长度不会超过100。

输出

 

排序后的图书信息列表,每条图书信息占一行,三个项目分别以” ”分隔,具体如样例。

输入样例 1 

6
Life_and_Death_Are_Wearing_Me_Out Mo_Yan 3000
Journey_to_the_West Wu_Cheng_en 2500
Dream_of_the_Red_Chamber Cao_Xueqin 2500
Water_Margin Shi_Nai_an 1700
Romance_of_the_Three_Kingdoms Luo_Guanzhong 1800
Big_Breasts_and_Wide_Hips Mo_Yan 3000

输出样例 1

name: Big_Breasts_and_Wide_Hips    author: Mo_Yan    sale: 3000
name: Life_and_Death_Are_Wearing_Me_Out    author: Mo_Yan    sale: 3000
name: Dream_of_the_Red_Chamber    author: Cao_Xueqin    sale: 2500
name: Journey_to_the_West    author: Wu_Cheng_en    sale: 2500
name: Romance_of_the_Three_Kingdoms    author: Luo_Guanzhong    sale: 1800
name: Water_Margin    author: Shi_Nai_an    sale: 1700
 1 //字典序比较
 2 
 3 bool cmp(const char *a, const char *b)
 4 {
 5     int len;
 6     int alen=strlen(a);
 7     int blen=strlen(b);
 8     len=alen>blen?blen:alen;
 9     for(int i=0;i<len;++i)
10     {
11         if(a[i]>b[i])
12             return true;//a的字典序比b后面 
13         else if(a[i]<b[i])
14             return false;//a的字典序比b前面 
15     }
16     
17     if(alen!=blen)
18     {
19         if(alen>blen)
20             return true;//a的字典序比b后面 
21         else
22             return false;//a的字典序比b前面 
23     }
24 } 
25 class Book {
26 private:
27     char name[102];
28     char author[102];
29     int sale;
30 public:
31     Book(){ }
32     Book(const char *a, const char *b, int c);
33     void print(){
34         cout<<"name: "<<name<<"	author: "<<author<<"	sale: "<<sale<<endl;
35     }
36     void input(){
37         cin>>name>>author>>sale;
38     }
39     friend bool operator<(const Book& x, const Book& y){
40         if(x.sale>y.sale)
41         {
42             return true;//靠前 
43         }
44         if(x.sale<y.sale)
45         {
46             return false;//靠后 
47         }
48         if(strcmp(x.name,y.name)!=0)
49         {
50             if(cmp(x.name,y.name))//x的字典序比y后面 
51             {
52                 return false;
53             }
54             return true;
55         }
56         
57         if(strcmp(x.author,y.author)!=0)
58         {
59             if(cmp(x.author,y.author))//x的字典序比y后面 
60             {
61                 return false;
62             }
63             return true;
64         }
65     }
66     ~Book(){
67     }
68 };
View Code
字符串反转排序
 

描述

 

利用string类对字符串进行(按反转后字典序)排序并输出,例如两个字符串为”aab”, “cba”,则”cba”应该排在”aab”之前,因为”cba”反转后为”abc”,”aab”反转后为”baa”

输入

 

第一行为一个整数N,表示字符串的数目。(0<N<50)

接下来是N行,每行一个字符串,其中字符串仅由小写字母组成,每个字符串长度不超过100,所有字符串均不相同。

输出

 

排完序以后的字符串,每个字符串占一行

输入样例 1 

6
cpp
class
object
stl
acm
bjfu

输出样例 1

stl
acm
cpp
class
object
bjfu

提示

 
bool cmp(const string &x,const string &y)
{
    return x<y;
}
int main()
{
    //现将字符串翻转,加入vector中sort,输出时再翻转变回原形
    
    int n;
    cin>>n;
    vector<string > vec;
    for(int i=0;i<n;++i)
    {
        string str;
        cin>>str;
        reverse(str.begin(),str.end());
        vec.push_back(str);
    } 
    sort(vec.begin(),vec.end(),cmp);
    for(int i=0;i<vec.size();++i)
    {
        string str;
        str=vec[i];
        reverse(str.begin(),str.end());
        cout<<str<<endl;
    } 
    return 0;
}
View Code
复数模板类
 

描述

 

复数模板类Complex包含实部和虚部,复数的模为实部和虚部的平方和再开根号。完成这个模板类,并通过测试函数

int main()
{
 Complex<int> ci1;
 cin >> ci1;
 Complex<int> ci2(2, 3);
 Complex<int> ci = ci1 + ci2;
 cout << ci.Mag() << endl;
 Complex<double> cd;
 cin >> cd;
 cout << setiosflags(ios::fixed) << setprecision(2);
 cout << cd.Mag() << endl;
 return 0;
}

输入

 

实部 虚部实部 虚部

输出

 

参见样例

输入样例 1 

1 1
1.5 1.5

输出样例 1

5
2.12
template <class T>
class Complex {

    public:    
        T real;
        T imag;
        Complex(T a=0,T b=0){
            real=a;
            imag=b;     
        } 
        
        friend Complex   operator +(const Complex &a,const Complex &b)
        {
            Complex c;
            c.real=a.real+b.real;
            c.imag=a.imag+b.imag;
//            cout<<a.imag<<","<<a.real<<endl;
//            cout<<b.imag<<","<<b.real<<endl;
//            cout<<"相加成功"<<"("<<c.real<<","<<c.imag<<")"<<endl; 
            return c;
        }
        
        friend istream &operator >>(istream &is,Complex &c)
        {
            is>>c.real>>c.imag;
        //    cout<<c.real<<","<<c.imag<<endl;
            return is;
        }
        
        double Mag()
        {
            
        //    cout<<"m="<<m<<endl;
            return sqrt((double)(real*real+imag*imag));
        }
};
View Code
原文地址:https://www.cnblogs.com/greenaway07/p/10509335.html