各位學弟學妹,注意獨立思考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 1000Name: The Art of Computer Programming Author: Donald Ervin Knuth Sale: 10001、注意輸出格式,每個圖書的信息占一行,信息的項目之間用\t分隔,最后以\n換行。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<<"\t"<<"Author: "<<author<<"\t"<<"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 }
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 }
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個字符的由英文大小寫字母組成的字符串)。
輸出一行,輸出客人的編號,姓名及總人數,空格分隔。
Peter2 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 }
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()<<"\nAddress: "<<Amy.getAddress()<<endl;
cout<<"\nThis is a copy of Amy:\n";
cout<<"Name: "<<copy_Amy.getName()<<"\nAddress: "<<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()<<"\nAddress: "<<Amy.getAddress()<<endl; cout<<"\nThis is a copy of Amy:\n"; cout<<"Name: "<<copy_Amy.getName()<<"\nAddress: "<<copy_Amy.getAddress()<<endl; return 0; }
日期相差天數(選做)
發布時間: 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 }
。
表面積和體積
發布時間: 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 594 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; }
....
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 MaryMary 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; }
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.5Car name:Benz Car color:black Car passager:3 Truck name:Dongfeng Truck color:white Truck capacity:8.5Vehicle中可包含名稱和顏色數據成員,並且有純虛函數以提供接口完成信息的顯示;在派生類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; }
圖書商品
發布時間: 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() << "\t" << num << "\t";
Item_base * p;
if (num >= 10) p = &bulk2;
else if (num >= 5) p = &bulk1;
else p = &book;
cout << p->net_price(num) << "\n";
}
return 0;
}
圖書的數量。
輸出購買的圖書的ISBN,它的數量以及總的價格。(具體見main中輸出的形式來輸出即可)
2 6 110-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() << "\t" << num << "\t"; Item_base * p; if (num >= 10) p = &bulk2; else if (num >= 5) p = &bulk1; else p = &book; cout << p->net_price(num) << "\n"; // printf("0-001-0001-1 2 20\n0-001-0001-1 6 54\n0-001-0001-1 11 88\n"); } return 0; }
//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; }
設計一個有理數類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 };
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) << "\n" << "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 }
描述
自增(++)和自減(--)操作符經常由諸如迭代器這樣的類實現,這樣的類提供類似於指針的行為訪問序列中的元
素。例如,可以定義一個類,該類指向一個數組並為該數組中的元素提供訪問檢查。假設,有以下類,它將處
理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
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 };
String類
使用以下的main函數進行測試:
int main()
{
String s;
s += "hello";
cout<<s<<endl;
String s1("String1");
String s2("copy of ");
s2 += "String1";
cout << s1 << "\n" << 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 };
..
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 }
..
排序描述
用函數模板的方式實現對不同數據類型的數組中的數據進行輸入、從小到大排序和輸出。
使用如下主函數測試你的模板
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 }
.
描述
設計一個單向鏈表的類模板,類模板的說明如下:
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;
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 };
..
#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 }
..
文件處理練習二描述
編寫程序,統計一篇英文文章中英文單詞的個數以及文章的總行數。(參考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 }
文件處理練習三描述
編寫程序,完成兩個英文文件的拼接。(參考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.\n"; 34 // exit(0); 35 // } 36 // if(!r2) 37 // { 38 // //cout<<"Cannot open the c2 file.\n"; 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]=='\n') 53 { 54 r1.put('\n'); 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 }
..
文件處理練習四描述
從文件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('\n'); 56 } 57 // 此處寫處理文件的代碼 58 f1.close(); 59 f2.close(); 60 return; 61 }
.
描述
編寫程序,打開一個英文的文本文件,在其中每一行的前面加上行號和一個空格符。(參考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 }
描述
編寫程序,利用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; }
描述
編寫程序,利用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; }
描述
編寫程序,定義一個結構體
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 }
描述
桌上有一疊牌,從第一張牌(即位於頂面的牌)開始從上往下依次編號為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; }
描述
現有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 }
描述
某城市有一個火車站,鐵軌鋪設如圖所示。有n節車廂從A方向駛入車站,按進站順序編號為1~n.你的任務是讓它們按照某種特定的順序進入B方向的鐵軌並駛出車站。為了重組車廂,你可以借助中轉站C。這是一個可以停放任意多節車廂的車站,但由於末端封頂,駛入C的車廂必須按照相反的順序駛出C。對於每個車廂,一旦從A移入C,就不能再回到A了;一旦從C移入B,就不能回到C了。換句話說,在任一時刻,只有兩種選擇:A->C和C->B。

輸入
輸入包含多組測試數據,每組數據的第一行是一個正整數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\n",flag?"Yes":"No"); } return 0; }
描述
丑數是指不能被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 }
描述
設計一個保存你個人信息的類,包含姓名和年齡。並使用以下代碼測試
int main()
{
string name;
int year;
cin >> name >> year;
PersonInfo info(name, year);
cout << "I am " << info.Name() << ", " << info.Age() << " years old.\n";
return 0;
}
輸入
姓名年齡
輸出
見樣例輸出
輸入樣例 1
master 999
輸出樣例 1
I am master, 999 years old.
提示
- 修改main函數會扣分
- 不使用類,沒有分數
- ","后面有一個空格,"."結束,沒有其它格式輸出
#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; } };
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.\nCPU type: "<<t1<<", CPU frequency: "<<c1<<" GHz\ndisk type: "<<t2<<", disk mount: "<<c2<<" T"<<endl; } };
描述
不同的動物既有共性也有個性。鳥類會飛,魚會游泳。請設計一個類層次結構表示。並通過以下測試
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 };
描述
不同的動物既有共性也有個性。鳥類會飛,魚會游泳。請設計一個類層次結構表示。並通過以下測試
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; };
描述
編寫程序,統計某旅館住宿客人的總數。要求輸入客人的姓名,輸出客人的編號(按先后順序自動生成)、姓名使用如下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!\n";
}
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; }
描述
in.txt是一個文本文件,保存了一些小數。文件第一行是小數個數m,后面一共m行小數。請讀入這些數據,求出平均數,並保存到out.txt中。請用C++的文件流實現這個功能,並將代碼放置到FileTest()中。注意本題要求:1.OJ測試通過。2.不修改代碼,本地附帶數據運行時能得到正確結果。
int main()
{
FileTest();
cout << "Hello C++\n";
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(); }
描述
描述:定義一個矩形類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 };
描述
用函數模板的方式實現對不同數據類型的數組中的數據進行輸入、輸出最小值。使用如下主函數測試你的模板
、、、
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]; }
..
..
描述
要求編寫函數模板,分別利用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; }
描述
實現一個Singer類,通過以下測試:
int main()
{
Singer s1,s2;
cin>>s1>>s2;
cout<<s1<<"\n"<<s2<<endl;
if(s1>s2)
cout<<s1.getName()<<"'s score is higher than "<<s2.getName()<<"'s.\n";
else if(s1==s2)
cout<<s1.getName()<<"'s score is equal to "<<s2.getName()<<"'s.\n";
else
cout<<s1.getName()<<"'s score is lower than "<<s2.getName()<<"'s.\n";
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 };
描述
設計一個函數模板,實現在一個給定的數組中查找給定的元素的值是否存在,如果存在則輸出該元素在數組中最小的下標,如果不存在,輸出-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 }
描述
編寫程序實現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; }
描述
以下是圖書類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。
輸出
排序后的圖書信息列表,每條圖書信息占一行,三個項目分別以”\t”分隔,具體如樣例。
輸入樣例 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<<"\tauthor: "<<author<<"\tsale: "<<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 };
描述
利用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; }
描述
復數模板類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)); } };
