码图C++作业

新增了目录和代码复制功能/doge


第七章 作业1

输出n!

#include <iostream>
using namespace std;

int factorial(int n){
    int result=0;
    if(n<0) cout<<"error!";
    else if(n==0||n==1) result=1;
    else result=factorial(n-1)*n;
    return result;
}
int main(){
    int n,m;
    cin>>n;
    if(n<=12){
    m=factorial(n);
    cout<<n<<"!="<<m<<endl;
    }
    else{
    m=factorial(12);
    cout<<"12!="<<m<<endl;
    }
    return 0;
}

将回车和制表符转成可见

void expand(char* s, char* t){
    int i, j;
    for (i = 0, j = 0; s[i] != '\0'; i++){
        switch (s[i]){
            case'\n':
                t[j++] = '\\';
                t[j++] = 'n';
                break;
            case'\t': 
                t[j++] = '\\';
                t[j++] = 't';
                break;
            default: 
                t[j++] = s[i];
                break;
        }
    }
    t[j] = '\0';
}

输出由星号组成的倒三角形

#include <iostream>
using namespace std;
int main(){
    int n;
    cin>>n;
    if(n%2==0||n<1||n>80) printf("error");
    else{
        for(int i=0;i<=(n-1)/2;i++){
            for(int j=0;j<=(n-i);j++){
                if(j<i) cout<<" ";
                else if(j==n-i) cout<<"\n";
                else cout<<"*";
            }
        }
    }
    return 0;
}

=========================================

第七章 作业2

100内能被3整除且个位为6

#include <iostream>
using namespace std;
int main(){
    int i,j;
    for(i=0;i<=9;i++){
        j=i*10+6;
        if(j%3!=0) continue;
        cout<<j;
    }
    return 0;
}

100~200内不被3和7整除

#include <iostream>
using namespace std;
int main(){
    for(int i=100;i<200;i++){
        if(i%3!=0&&i%7!=0) cout<<i;
    }
    return 0;
}

根据公式输出圆周率

#include<stdio.h>
int main ()
{
    double m=0;
    int i;
    for (i=1;i<=1e8/2;i++)
    {
        if(i%2==0) m=m-1/(2*(double)i-1);
        else m+=1/(2*(double)i-1);
    }

    if(i%2==0) m=m-1/(2*(double)i-1);
    else m+=1/(2*(double)i-1);

    printf("steps=%d ",i);
    printf("PI=%.5f",4*m);

    return 0;
}

输入年、月输出该月的天数

#include <iostream>
using namespace std;

int isleap(int n);
int main(){
    int a[12]={31,28,31,30,31,30,31,31,30,31,30,31};
    int y,m;
    scanf("%d%d",&y,&m);
    if(isleap(y)) a[1]++;
    printf("days:%d",a[m%12-1]);
    return 0;
}
int isleap(int n){
    if(n%400==0||(n%100!=0&&n%4==0)) return 1;
    else return 0;
}

升序排序,奇数在偶数之前

#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int a,i=0,odd=0,even=0,ev[10],od[10];
    for(i =1;i<=10;i++){
        scanf("%d",&a);
        if(a<0) break;
        if(a%2==0) ev[even++]=a;
        else od[odd++]=a;
    }sort(ev,ev+even);
    sort(od,od+odd);
    for(int i=0;i<odd;i++){
        printf("%d ",od[i]);
    }for(int i=0;i<even;i++){
        printf("%d ",ev[i]);
    }return 0;
}

复制字符串,将'\0'转义

#include<stdio.h>
int main(void)
{
    char a1[100],a2[100];
    int i;
    //gets(a1);
    scanf("%s",a1);
    for(i=0;i<100;i++){
        if(a1[i]=='\0')
            break;
        else a2[i]=a1[i];
    }
    //puts(a2);
    printf("%s\\0",a2);
    return 0;
}

矩阵乘法

#include <iostream>
void Matrix_Mul(int a[3][2], int b[2][4]);
int main(){
    int a[3][2]={{1,2},{3,4},{5,6}};
    int b[2][4]={{1,0,1,1},{0,1,0,1}};
    Matrix_Mul(a,b);
    return 0;
}
void Matrix_Mul(int a[3][2], int b[2][4]){
    int temp;
    for (int i=0;i<3;i++){
        for (int j=0;j<4;j++){
            temp=0;
            for (int k=0;k<2;k++){
                temp+=a[i][k]*b[k][j];
            }printf("%d",temp);
            if(j!=3){
                printf(" ");
            }else{
                printf(" \n");
            }
        }
    }
}

统计子字符串出现次数

#include <iostream>
#include <string.h>
int SubStrNum(char * str,char * substr);

int main(){
    char str[40] = "hhhhhh";
    char substr[40] ="hh";
    SubStrNum(str,substr);
    return 0;
}
int SubStrNum(char * str,char * substr){
    int len=strlen(str);
    int len2=strlen(substr);
    int count=0;
    int j=0;
    for (int i=0;i<len;i++){
        if(*(str+i)!=*(substr+j)){
            j=0;
        }else{
            j++;
            if(j==len2){
                count++;
                j=0;
            }
        }
    }printf("match times=%d",count);
    return count;
}

计算大整数的差

#include <iostream>
#include <string.h>
#include<stack>
using namespace std;
stack<int> answer;

int BigIntEqual(char* num1,char* num2);
int Sub(char* num1,char* num2);
int main(){
    char num1[40];
    char num2[40];

    scanf("%s %s",num1,num2);
    int a=BigIntEqual(num1,num2);
    if(a==1){
        int len=strlen(num1);
        printf("+");
        Sub(num1,num2);
    }else if(a==-1){
        int len=strlen(num2);
        printf("-");
        Sub(num2,num1);
    }else{
        printf("0");
    }
    return 0;
}

int BigIntEqual(char* num1,char* num2)
{   int len1=strlen(num1);
    int len2=strlen(num2);
    if(len1>len2)
        return 1;
    else if(len1<len2)
        return -1;
    else
    {
        int i=0;
        while(i<len1)
        {
            if(*(num1+i)>*(num2+i))
                return 1;
            else if(*(num1+i)<*(num2+i))
                return -1;
            else
                i++;
        }
    }
    return 0;
}
int Sub(char* num1,char* num2){
    int len1=strlen(num1);len1--;
    int len2=strlen(num2);len2--;
    int jinwei=0;
    for(;len2>=0;len2--,len1--){
        int temp=*(num1+len1)-*(num2+len2)-jinwei;
        if(temp>=0){
            answer.push(temp);
            jinwei=0;
        }else{
            answer.push(temp+10);
            jinwei=1;
        }
    }for(;len1>=0;len1--){
        int temp=*(num1+len1)-'0'-jinwei;
        if(temp>=0){
            answer.push(temp);
            jinwei=0;
        }else{
            answer.push(temp+10);
            jinwei=1;
        }
    }
    int size=answer.size();
    for(int i=0;i<size;i++){
        printf("%d",answer.top());
        answer.pop();
    }
    return 0;
}

输入两个参数和操作符并计算结果

#include "iostream"
#include <math.h>
using namespace std;
int main(){
    char c;
    float a,b,result(0);
    int tag(1);
    cin>>a>>b>>c;
    switch(c){
        case '+' :result = a+b; break;
        case '-' :result = a-b;break;
        case '*' :result = a*b;break;
        case  '/':
        if(fabs(b)<1e-6){
            cout<<"divide 0"<< endl;
            tag=0;
            break;
        }
            result = a/b;
            cout<<result<<endl;
            break;
        default:
            tag =0;
            cout<<"invalid operation"<<endl;
            break;
    }
    if(tag){
        cout<<result<<endl;
    }
    return 0;
}

=========================================

第八章 作业1

输出类的X和Y值

#include <iostream>
using namespace std;
class Location{
private :
    int X,Y;
public:
    void init(int initX,int initY){
        X = initX;
        Y = initY;
    }
    int GetX(){
        return X;
    }
    int GetY(){
        return Y;
    }
};
int main(){
    Location A1;
    A1.init(20,90);
    Location &rA1=A1;
    cout<<rA1.GetX()<<rA1.GetY();
    return 0;
}

实现Clock类

#include<iostream>
#include"Clock.h"
using namespace std;
Clock::Clock(int h,int m,int s)
{
	if(h<0||h>23) hour=0;
	else hour=h;
	if(m<0||m>59) minute=0;
	else minute=m;
	if(s<0||s>59) second=0;
	else second=s;
}
void Clock::SetAlarm(int h,int m,int s)
{
	if(h>23) Ahour=0;
	else Ahour=h;
	if(m>59) Aminute=0;
	else Aminute=m;
	if(s>59) Asecond=0;
	else Asecond=s;
	return ;
}
void Clock::run()
{
	second+=1;
	if(second>59)
	{second=0;minute+=1;}
	if(minute>59)
	{minute=0;hour+=1;}
	if(hour>23)
	{hour=0;}
	if((hour==Ahour)&&(minute==Aminute)&&(second==Asecond))
		cout<<"Plink!plink!plink!..."<<endl;
	return ;
}

实现User类

#include <iostream>
#include <string.h>
using namespace std;

class User{
private:
    char name[1000][10];
    char pass[1000][10];
    int num;
public:
    int login(char *name1,char * pass1){
        for(int i=0;i<num;i++){
            if(strcmp(name[i],name1)==0){
                if(strcmp(pass[i],pass1)==0){
                    return i;
                }else{
                    break;
                }
            }
        }return -1;
    }
    User(char * name1,char * pass1){
        num=0;
        strcpy(name[num],name1);
        strcpy(pass[num],pass1);
        num++;
    }
    void AddUser(char * name1,char * pass1){
        strcpy(name[num],name1);
        strcpy(pass[num],pass1);
        num++;
    }
};

int main(){
    char name[10],name1[10],pass[10],pass1[10];
    cin>>name>>pass>>name1>>pass1;
    User user("LiWei","liwei101");
    user.AddUser(name,pass);
    if (user.login(name1,pass1) >=0)
    {
        cout<<"Success Login!"<<endl;
    }
    else{
        cout<<"Login failed!"<<endl;
    }
    return 0;
}

=========================================

第八章 作业2

实现三角形类

#include <iostream>
#include <math.h>
using namespace std;

class Ctriangle{
private:
    double a,b,c;
public:
    Ctriangle(double aa,double bb,double cc){
        a=aa;b=bb;c=cc;
    };
    double GetPerimeter(){
        double perimeter=a+b+c;
        return perimeter;
    };
    double GetArea(){
        double area;
        double p=(a+b+c)/2;
        area=sqrt(p*(p-a)*(p-b)*(p-c));
        return area;
    };
    void display(){
        cout<<"Ctriangle:a="<<a<<",b="<<b<<",c="<<c<<endl;
        return;
    };
};

int main(){
    double a,b,c;
    cin>>a>>b>>c;
    Ctriangle T(a,b,c);
    T.display();
    cout<<"Perimeter:"<<T.GetPerimeter()<<endl;
    cout<<"Area:"<<T.GetArea()<<endl;
    return 0;
}

实现Point类

#include <iostream>
#include <math.h>
using namespace std;

class Point {
private:
    double x,y;
public:
    Point(double a,double b){
        x=a;y=b;
    }
    double Distance(const Point c){
        double ans=pow((x-c.x),2)+pow((y-c.y),2);
        ans=sqrt(ans);
        return ans;
    }
};

int main(){
    double a,b,c,d;
    cin>>a>>b>>c>>d;
    Point A(a,b),B(c,d);
    cout<<A.Distance(B)<<endl;
    return 0;
}

实现Date类

#include <iostream>
using namespace std;

class Date{
public:
    Date(int y =1996,int m=1,int d=1);
    int days(int year,int month);
    void NewDay();
    void display(){
        cout<<year<<"-"<<month<<"-"<<day<<endl;
    }
private:
    int year; 
    int month; 
    int day;
};
Date::Date(int y,int m,int d){
    if(m<1||m>12){
        cout<<"Invalid month!"<<endl;
        m=1;
    }if(d<1||d>days(y,m)){
        cout<<"Invalid day!"<<endl;
        d=1;
    }year=y;month=m;day=d;
}
void Date::NewDay(){
    day++;
    if(day>days(year,month)){
        day=1;month++;
        if(month==13){
            month=1;year++;
        }
    }
}
int Date::days(int year,int month){
    int ddays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
    if((year%4==0&&year%100!=0)||year%400==0){
        ddays[2]=29;
    }else{
        ddays[2]=28;
    }return ddays[month];
}
int main(){
    Date d(1993,13,32);
    d.display();
    return 0;
}

实现Student类

#include <iostream>
#include <string.h>
using namespace std;

class Student
{
private:
    char name[20];
    char id[20];
    int grade1,grade2,grade3;
    static int tgrade1,tgrade2,tgrade3;
public:
    Student(char *name1,char *id,int g1,int g2,int g3);
    void display();
    static double average1(){
        double ans=tgrade1/3.0;
        return ans;
    }
    static double average2(){
        double ans=tgrade2/3.0;
        return ans;
    }
    static double average3(){
        double ans=tgrade3/3.0;
        return ans;
    }
};
int Student::tgrade1=0,Student::tgrade2=0,Student::tgrade3=0;

Student::Student(char *name1,char *id1,int g1,int g2,int g3)
{
    strcpy(name,name1);
    strcpy(id,id1);
    grade1=g1;tgrade1+=g1;
    grade2=g2;tgrade2+=g2;
    grade3=g3;tgrade3+=g3;
}

void Student::display(){
    cout<<name<<" "<<id<<" "<<grade1<<" "<<grade2<<" "<<grade3<<endl;
}


int main(){
    Student *stu1,*stu2,*stu3;
    char name1[10],name2[10],name3[10];
    char num1[12],num2[12],num3[12];
    int grade1[3],grade2[3],grade3[3];
    cin>>name1>>num1>>grade1[0]>>grade1[1]>>grade1[2];
    cin>>name2>>num2>>grade2[0]>>grade2[1]>>grade2[2];
    cin>>name3>>num3>>grade3[0]>>grade3[1]>>grade3[2];
    stu1 = new Student(name1,num1,grade1[0],grade1[1],grade1[2]);
    stu2 = new Student(name2,num2,grade2[0],grade2[1],grade2[2]);
    stu3 = new Student(name3,num3,grade3[0],grade3[1],grade3[2]);

    stu1->display();
    stu2->display();
    stu3->display();

    cout<<"The average grade of course1:"<<stu2->average1()<<endl;
    cout<<"The average grade of course2:"<<stu2->average2()<<endl;
    cout<<"The average grade of course3:"<<stu2->average3()<<endl;
    return 0;
}

完成String类

#include <string.h>
#include <iostream>
using namespace std;
class String{
private:
    char *mystr;
    int len;
public:
    String(){
        len =0;
        mystr =NULL;
    }
    String(const char* p){
        len = strlen(p);
        mystr = new char[len+1];
        strcpy(mystr,p);
    }
    String(String &s){
        len = s.len;
        if (len !=0)
        {
            mystr = new char[len+1];
            strcpy(mystr,s.mystr);
        }
    }
    ~String(){
        if (mystr != NULL)
        {
            delete []mystr;
            mystr =NULL;
            len = 0;
        }
    }

    char *GetStr(){return mystr;}
    void ShowStr(){cout<<mystr;}

    bool IsSubstring(const char *str);
    bool IsSubstring(const String &str);
    int str2num();
    void toUppercase();
};

bool String::IsSubstring(const String &str) {
    int j=0;
    for(int i=0;i<len;i++){
        if(*(mystr+i)==*(str.mystr+j)){
            if(j==str.len-1) return true;
            else j++;
        }else{
            j=0;
        }
    }
    return false;
}

bool String::IsSubstring(const char *str) {
    int j=0;
    int llen=strlen(str);
    for(int i=0;i<len;i++){
        if(*(mystr+i)==*(str+j)){
            if(j==llen-1) return true;
            else j++;
        }else{
            j=0;
        }
    }
    return false;
}

int String::str2num() {
    int ans=0;
    for(int i=0;i<len;i++){
        if(*(mystr+i)<='9'&&*(mystr+i)>='0'){
            ans=ans*10+(*(mystr+i)-'0');
        }
    }
    return ans;
}

void String::toUppercase() {
    for(int i=0;i<len;i++){
        if(*(mystr+i)<='z'&&*(mystr+i)>='a'){
            *(mystr+i)=*(mystr+i)-'a'+'A';
        }
    }return;
}

int main(){

    String a("abddddddbb");
    if(a.IsSubstring("dddc")){
        cout<<"yes";
    }
    return 0;
}

=========================================

第9章 作业1

继承Point类

#include <iostream>
using namespace std;
const float pi=3.14;
class Point{
public:
	Point(float xx, float yy){
		x = xx;
		y =yy;
	}
private:
	float x;
	float y;
};

class Rectangle :public Point{
public:
	Rectangle(float xx,float yy,float w,float h);
	float Area();
private:
	float width;
	float high;
};

class Circle:public Point{
public:
	Circle(float xx,float yy,float r);
	float Area();
private:
	float radius;
};

Rectangle::Rectangle(float xx,float yy,float w,float h):Point(xx,yy)
{
	width=w,high=h;
}
Circle::Circle(float xx,float yy,float r):Point(xx,yy)
{
	radius=r;
}
float Rectangle::Area()
{
	return width*high;
}
float Circle::Area()
{
	return radius*radius*pi;
}

重载《运算符

#include <iostream>
using namespace std;

class Date{
public:
    Date(int y=1996,int m=1,int d=1){
        day = d;
        month = m;
        year = y;
        if (m>12 || m<1)
        {
            month=1;
        }
        if (d>days(y,m))
        {
            cout<<"Invalid day!"<<endl;
            day=1;
        }
    }
    int days(int y,int m){
        int ddays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
        if((y%4==0&&y%100!=0)||y%400==0){ //闰年,,搞错了。。
            ddays[2]=29;
        }else{
            ddays[2]=28;
        }return ddays[m];
    }
    void display(){
        cout<<year<<"-"<<month<<"-"<<day<<endl;
    }
    friend ostream& operator<<(ostream&out,Date &obj){
        obj.display();
        return out;
    }
private:
    int year;
    int month;
    int day;
};

int main(){
    int y,m,d;
    cin>>y>>m>>d;
    Date dt(y,m,d);
    cout<<dt;
    return 0;
}

(多态)填空题04

#include <iostream>
using namespace std;
class Base{
public:
    virtual void fun(){cout<<1<<endl;}
};
class Derived:public Base{
public:
    void fun(){cout<<2<<endl;}
};
int main(){
    Base *p = new Derived;
    p->fun();
    delete p;
    return 0;
}

(多态)Set类

#include <iostream>
using namespace std;
class Set{
private:
    int n;
    int * pS; //集合元素
public:
    Set(){n = 0;pS =NULL;}
    Set(Set &s){
        n = s.n;
        if (n !=0)
        {
            pS= new  int[n+1];
            for (int i =1;i<=n;i++) //集合的下标从1开始,集合中不能有重复元素
                pS[i] = s.pS[i];
        }
    }
    ~Set(){
        if (pS)
        {
            delete []pS;
            pS = NULL;
            n =0;
        }
    }
    void ShowElement()const{ //输出集合的元素
        int temp = 0;
        for(int i=1;i<n;i++)  //这好像少了一个元素?  从小到大排列
        {
            for(int j=i+1;j<n;j++)
            {
                if(pS[i] > pS[j])
                {
                    temp = pS[i];
                    pS[i] = pS[j];
                    pS[j] = temp;
                }
            }
        }
        cout<<"{";
        for(int i =1;i<n;i++)
            cout <<pS[i]<<",";
        if (IsEmpty())
            cout<<"}"<<endl;
        else cout<<pS[n]<<"}"<<endl;  //输出的最后一个元素好像没有排序吧
    }
    bool IsEmpty()const{return n?false:true;} //判断集合是否为空
    int size(){return n;}
    bool IsElement(int e)const {
        for (int i =1;i<=n;i++)
            if (pS[i] ==e)
                return true;
        return  false;
    }
    bool operator <=(const Set &s)const;//this <= s判断当前集合是否包于集合s
    bool operator ==(const Set &s)const; //判断集合是否相等
    Set & operator +=(int e);    // 向集合中增减元素e
    Set & operator -=(int e);    //删除集合中的元素e

    Set operator |(const Set &s)const;  //集合并
    Set operator &(const Set &s)const;//集合交
    Set operator -(const Set &s)const; //集合差
};

//#include "CSet.h"

bool Set::operator<=(const Set &s) const {  //看清楚题目,是当前集合是否属于另一个集合。。。jiuzhe?
    if(s.n<n){
        return false;
    }
    for(int i=1;i<=n;i++){
        if(!s.IsElement(pS[i])){
            return false;
        }
    }
    return true;
}

bool Set::operator==(const Set &s) const {
    if(s.n!=n){
        return false;
    }
    for(int i=1;i<=s.n;i++){
        if(!IsElement(s.pS[i])){
            return false;
        }
    }
    return true;
}

Set &Set::operator+=(int e) {  //new分配的内存空间不够怎么办
    if(IsEmpty()){
        pS=new int [100];  //分配不够会错误
    }
    if(!IsElement(e)){
        n++;
        pS[n]=e;
    }
    return *this;  //不知道对不对
}

Set &Set::operator-=(int e){
    for (int i =1;i<=n;i++)
        if (pS[i] ==e){
            for(;i<n;i++){
                pS[i]=pS[i+1];
            }n--;
            break;
        }
    return *this;
}

Set Set::operator|(const Set &s) const {
    Set S;//用第二种构造函数直接赋值的时候报错了,应该是可以的
    S.n=n;
    S.pS = new int[n+s.n+1];
    for(int i=1;i<=n;i++){
        S.pS[i]=pS[i];
    }
    for (int i=1;i<=s.n;i++){
        if(!S.IsElement(s.pS[i])){
            S.pS[++S.n]=s.pS[i];
        }
    }
    return S;
}

Set Set::operator&(const Set &s) const {
    Set S;
    S.n=0;
    S.pS = new int[n+s.n+1];
    for (int i=1;i<=s.n;i++){
        if(IsElement(s.pS[i])){
            S.pS[++S.n]=s.pS[i];
        }
    }
    return S;
}

Set Set::operator-(const Set &s) const {
    Set S;
    S.n=0;
    S.pS = new int[n+1];
    for (int i=1;i<=n;i++){
        if(!s.IsElement(pS[i])){
            S.pS[++S.n]=pS[i];
        }
    }
    return S;
}


int main(){
    Set s1,s2;
    s1+=1;s1+=3;s2+=2;s2+=1;
    (s1-s2).ShowElement() ;//{1,2}
    return 0;
}

=========================================

第九章 作业2

C++Test_Shape

#include<iostream>
#include"ShapeFactory.h"
using namespace std;


class Triangle :public ShapeFactory
{
private:
	float a, b, c;
public:
	Triangle(float a0, float b0, float c0)
	{
		a = a0; b = b0; c = c0;
	}
	float Circumstance()
	{
		return a + b + c;
	}

};

class Quadrangle :public ShapeFactory
{
private:
	float a, b, c, d;
public:
	Quadrangle(float a0, float b0,float c0,float d0)
	{
		a = a0, b = b0, c = c0, d = d0;
	}
	float Circumstance()
	{
		return a + b + c+d;
	}
}; 

class Circle :public ShapeFactory
{
private:
	float r;
public:
	Circle(float r0)
	{
		r = r0;
	}
	float Circumstance()
	{
		return r*2*3.14;
	}
};

ShapeFactory* ShapeFactory::Create(float a, float b, float c)
{
	ShapeFactory* p = new Triangle(a, b, c);
	return p;
}
ShapeFactory* ShapeFactory::Create(float a, float b, float c, float d)
{
	ShapeFactory* p = new Quadrangle(a, b, c, d);
	return p;
}
ShapeFactory* ShapeFactory::Create(float r)
{
	ShapeFactory* p = new Circle(r);
	return p;
}

C++-简单计算器

#pragma once
class CNumberFactory
{
public:
    virtual void Add(int number) {};
    virtual void Sub(int number) {};
    virtual int GetValue() {return -1;};

    virtual void SetValue(int number) {};
    CNumberFactory *Create();
};


// #include "CNumberFactory.h"
#include <iostream>
using namespace std;
class CNumber : public CNumberFactory{
private:
    int num;
public:
    void Add(int number){
        num+=number;
    }
    void Sub(int number) {
        num-=number;
    }
    int GetValue() {
        return num;
    }
    void SetValue(int number) {
        num=number;
    }
};


CNumberFactory *CNumberFactory::Create()
{
    CNumberFactory * p = new CNumber();
    return new CNumber();
}

继承Building类

#include <cstring>
#include <iostream>
using namespace std;
class Building{
public:
    Building(char *name,int floor,int room,int area){
        strcpy(this->name,name);
        this->floor = floor;
        this->room = room;
        this->area = area;
    }
    virtual void display(){
        cout<<"Name:"<<name<<endl;
        cout<<"Floor:"<<floor<<endl;
        cout<<"Room:"<<room<<endl;
        cout<<"Area:"<<area<<endl;
    }
    Building * createTeachBuilding(char *name,int floor,int room,int area,char *function);
    Building * creatDormBuilding(char *name,int floor,int room,int area,int peoples);
protected:
    char name[20];
    int floor;
    int room;
    float area;

};
class TeachBuilding : public Building{
private:
    char function[20];
public:
    TeachBuilding(char *name,int floor,int room,int area,char *function):Building(name,floor,room,area){
        strcpy(this->function,function);
    }
    void display(){
        cout<<"Name:"<<name<<endl;
        cout<<"Floor:"<<floor<<endl;
        cout<<"Room:"<<room<<endl;
        cout<<"Area:"<<area<<endl;
        cout<<"Function:"<<function<<endl;
    }
};

class DormBuilding : public Building{
private:
    int peoples;
public:
    DormBuilding(char *name,int floor,int room,int area,int people):Building(name,floor,room,area){
        peoples = people;
    }
    void display(){
        cout<<"Name:"<<name<<endl;
        cout<<"Floor:"<<floor<<endl;
        cout<<"Room:"<<room<<endl;
        cout<<"Area:"<<area<<endl;
        cout<<"Peoples:"<<peoples<<endl;
    }

};
Building* Building::createTeachBuilding(char *name,int floor,int room,int area,char *function){
    Building * p = new TeachBuilding(name,floor,room,area,function);
    return p;
}

Building * Building::creatDormBuilding(char *name,int floor,int room,int area,int peoples){
    Building * p = new DormBuilding(name,floor,room,area,peoples);
    return p;
}

实现RoundTable类

#include <iostream>
#include <cstring>
using namespace std;
class Table{
private:
    float high;

public:
    Table(float h){
        high=h;
    }
    float GetHigh(){
        return high;
    }

};

class Circle{
private:
    float radius;
public:
    Circle(float r){
        radius=r;
    }
    float GetArea(){
        return radius*3.14*radius;
    }
};

class RoundTable: public Table,
                  public Circle{
private:
    char color[20];
public:
    RoundTable(float r,float h,char* c):Table(h),Circle(r){
        strcpy(color,c);
    }
    char * GetColor(){
        return color;
    }
};

int main(){
    float radius,high;
    char color[20];
    cin>>radius>>high>>color;

    RoundTable RT(radius,high,color);
    cout<<"Area:"<<RT.GetArea()<<endl;
    cout<<"High:"<<RT.GetHigh()<<endl;
    cout<<"Color:"<<RT.GetColor()<<endl;
    return 0;
}

完成NewClock类

#include"Clock.h"

class NewClock :public Clock {
	int hour, minute, second;
public:
	NewClock(int h, int m, int s) : Clock(h, m, s) {

		hour = getHour();
		minute = getMinute();
		second = getSecond();
	}
	void showTime() {

		if (hour < 12)
		{
			cout << "Now:" << hour << ":" << minute << ":" << second << "AM" << endl;
		}
		else
		{
			cout << "Now:" << hour - 12 << ":" << minute << ":" << second << "PM" << endl;
		}
	}
	void run() {
		second = second + 1;
		if (second>59)
		{
			second = 0;
			minute += 1;
		}
		if (minute>59)
		{
			minute = 0;
			hour += 1;
		}
		if (hour>23)
		{
			hour = 0;
		}
	}
};
Clock* Clock::createNewClock(int h, int m, int s) {
	return new NewClock(h, m, s);
}

ClockWithDate类

#include <iostream>
using namespace std;
class Clock{
public:
    Clock(int h,int m,int s){
        hour =(h>23? 0:h);
        minute = (m>59?0:m);
        second = (s>59?0:s);
    }
    virtual void run(){
        second = second+1;
        if (second>59)
        {
            second =0;
            minute+=1;
        }
        if (minute>59)
        {
            minute =0;
            hour+=1;
        }
        if (hour>23)
        {
            hour =0;
        }
    }
    virtual void showTime(){
        cout<<"Now:"<<hour<<":"<<minute<<":"<<second<<endl;
    }
    int getHour(){return hour;}
    int getMinute(){return minute;}
    int getSecond(){return second;}

    Clock * createClockWithDate(int h,int m,int s,int year,int month,int day);
protected:
    int hour;
    int minute;
    int second;
};

class Date{
public:
    Date(int y=1996,int m=1,int d=1){
        day =d;
        year =y;
        month =m;
        if (m>12||m<1)
        {
            m=1;
        }
        if(d>days(y,m)){
            day = 1;
        }
    };
    int days(int year,int month);
    void NewDay();
    void display(){
        cout<<year<<"-"<<month<<"-"<<day<<endl;
    }
protected:
    int year;
    int month;
    int day;
};


/// #include "ClockAndDate.h"

int Date::days(int year, int month) {
    int ddays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
    if((year%4==0&&year%100!=0)||year%400==0){ //闰年,,搞错了。。
        ddays[2]=29;
    }else{
        ddays[2]=28;
    }
    return ddays[month];
}

void Date::NewDay() {
    day+=1;
    if(day>days(year,month)){
        day=1;
        month++;
    }if(month==13){
        month=1;
        year++;
    }
}

class ClockWithDate : public Clock, public Date{
public:
    ClockWithDate(int h,int m,int s,int y,int mm,int d):Clock(h,m,s),Date(y,mm,d){}
    void run(){
        Clock::run();
        if(hour==0&&minute==0&&second==0){
            NewDay();
        }
    }
    void showTime(){
        Clock::showTime();
        display();
    }
};


Clock* Clock::createClockWithDate(int h,int m,int s,int year,int month,int day){
    return new ClockWithDate(h,m,s,year,month,day);
}

扩展String类

#include<stdio.h>
#include <iostream>
#include<cstring> 
#include<string>
using namespace std;
class String{
protected:
	char *mystr;
	int len;
public:
	String(const char *p){
		len = strlen(p);
		mystr = new char[len+1];
		strcpy(mystr,p);
	}
	~String(){
		if (mystr !=NULL)
		{
			delete []mystr;
			mystr = NULL;
			len = 0;
		}
	}
	void showStr(){cout <<mystr;}
	char * GetStr(){return mystr;}
	virtual bool IsSubString(const char *str){
		int i,j;
		for (i =0;i<len;i++)
		{
			int k = i;
			for (j =0;str[j] !='0\0';j++,k++)
			{
				if (str[j]!= mystr[k]) break;
			}
			if(str[j] =='\0') return true;
		}
		return false;
	}
};

class EditString:public String{
public:
	EditString(const char *p):String(p){}
	int IsSubString(int start, const char *str);
	void EditChar(char s, char d); 
	void EditSub(char * subs,char *subd); 

	void DeleteChar(char ch);  
	void DeleteSub(char * sub); 

};
int EditString::IsSubString(int start, const char *str)
{
	int i,j;
	for(i=start;i<len;i++)
	{
		int k=i;
		for(j=0;str[j];j++,k++)
		{
			if(str[j]!=mystr[k])break;
		}
		if(str[j]=='\0')return i;
	}
	return -1;
}
void EditString::EditChar(char s, char d)
{
	for(int i=0;i<len;i++)
	{
		if(mystr[i]==s)
		mystr[i]=d;
	}
}
void EditString::EditSub(char * subs,char *subd)
{ 
	int start=EditString::IsSubString(0,subs);
	if(start<0)return;
	else
	{
		int i=0,j=0;
		int l1=strlen(subs);
	    int l2=strlen(subd);
	    char newstr[25];
	    for(;i<25;i++)
	    {
	    	newstr[i]='\0';
	    }
	    while(start!=-1)
	    {
	    	for(i=0;j<start;j++,i++)
	    	{
	    		newstr[i]=mystr[j];
	    	}
	    	for(int k=0;k<l2;k++,i++)
	    	{
	    		newstr[i]=subd[k];
	    	}
	    	start=EditString::IsSubString(start+l1,subs);
	    	j=j+l1;
	    	if(start==-1)
		    	for(;j<len;j++,i++)
		    	{
		    		newstr[i]=mystr[j];
		    	}
	    }
	    for(i=0;i<len;i++)
	    { 
	    	mystr[i]='\0';
	    } 
	    strcpy(mystr,newstr);
//	    int L=strlen(mystr);
//	    for(int i=0;i<L;i++)
//	    cout<<mystr[i]<<endl;
	    return;
	} 
} 
void EditString::DeleteChar(char ch)
{
	for(int i=0;mystr[i];i++)
	{
		if(mystr[i]==ch)
		{
			for(int j=i;mystr[j];j++)
			{
				mystr[j]=mystr[j+1];
			}
			i--;
		}
	}
//	for(int k=0;k<len;k++)
//	cout<<mystr[k];
//	cout<<endl;
}
void EditString::DeleteSub(char * sub)
{
	int start=EditString::IsSubString(0,sub);
	if(start<0)return;
	else
	{
		int L=strlen(sub);
		char newstr[25];
		for(int i=0;i<25;i++)
		{
			newstr[i]='\0';
		}
		int i=0,j=0;
		while(start>=0)
		{
		for(;j<start;i++,j++)
		{
			newstr[i]=mystr[j];
		}	
		j=j+L;
		start=EditString::IsSubString(j,sub);
		if(start==-1)
		{
			for(;j<len;i++,j++)
			newstr[i]=mystr[j];
		}
		}
		for(i=0;mystr[i];i++)
		{
		mystr[i]='\0';	
		}	
		strcpy(mystr,newstr);
		for(i=0;mystr[i];i++)
		{
			cout<<mystr[i];
		}
		cout<<endl;
	}
}

完成Location类

#include "Location.h"
#include <string.h>
Location &Location::operator +(Location &offset)
{
    this->x += offset.x;
    this->y += offset.y;
    return *this;
}
Location &Location::operator-(Location &offset)
{
    this->x -= offset.x;
    this->y -= offset.y;
    return *this;
}

工具类Vehicle

#include"Vehicle.h"
class Car :public Vehicle
{
public:
	Car() { cout << "Car constructor..." << endl; }
	virtual void display()const
	{
		cout << "This is a car!"<<endl;
	}
	~Car() { cout << "Car destructor..." << endl; }
};

class Truck :public Vehicle
{
public:
	Truck() { cout << "Truck constructor..." << endl; }
	virtual void display()const
	{
		cout << "This is a truck!"<<endl;
	}
	~Truck() { cout << "Truck destructor..." << endl; }
};

class Boat :public Vehicle
{
public:
	Boat() { cout << "Boat constructor..." << endl; }
	virtual void display()const
	{
		cout << "This is a boat!"<<endl;
	}
	~Boat() { cout << "Boat destructor..." << endl; }
};

Vehicle* Vehicle::createCar() { return new Car(); }
Vehicle* Vehicle::createTruck() { return new Truck(); }
Vehicle* Vehicle::createBoat() { return new Boat(); }

抽象类Shape

#include <iostream>
using namespace std;
class Shape{
public:
    Shape(){}
    ~Shape(){}
    virtual double GetArea()=0;
    virtual double GetPerimeter()=0;
    static Shape* createRectangle(double length,double width);
    static Shape* createCircle(double radius);
};
class Rectangle: public Shape{
private:
    double length,width;
public:
    double GetArea(){
        return length*width;
    }double GetPerimeter(){
        return 2*(length+width);
    }
    Rectangle(double l,double w){
        length=l;width=w;
    }
};


class Circle: public Shape{
private:
    double radius;
public:
    double GetArea(){
        return 3.14*radius*radius;
    }double GetPerimeter(){
        return 2*3.14*radius;
    }Circle(double r){
        radius=r;
    }
};

Shape * Shape::createRectangle(double l,double w){return new Rectangle(l,w);}
Shape * Shape::createCircle(double r){return new Circle(r);}

=========================================

第十章 作业1

PS:让码图编译会儿~

get_sum

template<class T>
T get_sum(T* array, int n)
{
	T sum = 0;
	for (int i = 0; i < n; i++)
	{
		sum += array[i];
	}
	return sum;
}

node append

template <typename DataType>
class node
{
private:
    DataType data;
    node *next;

public:
    node(){};
    void set_value(DataType d)
    {
        data = d;
    }
    DataType get_value()
    {
        return data;
    }
    node *get_next()
    {
        return next;
    }
    void append(node *n)
    {
        next = n;
    }
};

异常处理

class A{
public:
    int err;
    A(int index){
        err=index;
    }
};
class B{
public:
    int err;
    B(int divisor){
        err=divisor;
    }
};

命名空间ns1

int x=1,y=2;
    namespace ns2{
        char x='a',y='b';
        int add_one(int a){
            return a+1;
        }
    }

=========================================

第10章 作业2

get_max

template<class T>
T get_max(T* array, int n)
{
	T max=array[0];
	for (int i = 1; i < n; i++)
	{
        if(array[i]>max){
            max=array[i];
        }
	}
	return max;
}

get_min

template<class T>
T get_min(T* array, int n)
{
	T min=array[0];
	for (int i = 1; i < n; i++)
	{
        if(array[i]<min){
            min=array[i];
        }
	}
	return min;
}

node insert

template <typename DataType>
class node
{
private:
    DataType data;
    node *next;

public:
    node(){};
    void set_value(DataType d)
    {
        data = d;
    }
    DataType get_value()
    {
        return data;
    }
    node *get_next()
    {
        return next;
    }
    void insert(node *n)
    {
        n->next=this;
    }
};

异常捕获

    catch (int aa){
        if(aa!=0){
            cout << aa << " out of bound" << endl;
        }else{
            cout << "divide by "<< aa << endl;
        }
    }

命名空间nsA

int x=1,y=2;
    namespace nsB{
        char x='a',y='b';
        int add_something(int a){
            return a+2;
        }
    }
    int add_something(int a){
        return a+1;
    }
posted @ 2021-10-29 16:24  酸柚子sour  阅读(1927)  评论(0)    收藏  举报
Akizuki-Kanna