美文网首页
CPP_Basic_Code_P9.1-PP9.6.4

CPP_Basic_Code_P9.1-PP9.6.4

作者: 贴墙上的咖啡 | 来源:发表于2017-05-03 10:25 被阅读0次

    CPP_Basic_Code_P9.1-PP9.6.4

    //  The Notes Created by Z-Tech on 2017/2/17.
    //  All Codes Boot on 《C++ Primer Plus》V6.0
    //  OS:MacOS 10.12.4
    //  Translater:clang/llvm8.0.0 &g++4.2.1
    //  Editer:iTerm 2&Sublime text 3
    //  IDE: Xcode8.2.1&Clion2017.1
    
    //P9.1-P9.3
    cmake_minimum_required(VERSION 3.6)
    project(CLion_Version)
    
    set(CMAKE_CXX_STANDARD 11)
    
    set(SOURCE_FILES coordin.h file1.cpp file2.cpp)//资源文件包含说明
    add_executable(CLion_Version ${SOURCE_FILES})//可使用指定源文件引入可执行文件
    
    coordin.h
    #ifndef CLION_VERSION_COORDIN_H
    #define CLION_VERSION_COORDIN_H
    
    struct polar//极坐标结构
    {
        double distance;
        double angle;
    };
    struct rect//直角坐标结构
    {
        double x;
        double y;
    };
    
    polar rect_to_polar(rect xypos);//直角转为极坐标
    void show_polar(polar dapos);//显示极坐标
    
    #endif //CLION_VERSION_COORDIN_H
    
    file1.cpp
    #include <iostream>
    #include "coordin.h"
    
    int main()
    {
        using namespace std;
        rect rplace;//声明两个结构以存储输入的数据
        polar pplace;
    
        cout<<"Enter the x and y value: ";
        while (cin>>rplace.x>>rplace.y)//连续使用cin可行,且忽略空格等
        {
            pplace=rect_to_polar(rplace);//结果赋值给第二个结构
            show_polar(pplace);//显示
            cout<<"Next two numbers (q to quiit): ";
        }
        cout<<"Done.\n";
        return 0;
    }
    
    file2.cpp
    #include <iostream>
    #include <cmath>
    #include "coordin.h"
    
    
    polar rect_to_polar(rect xypos)
    {
        using namespace std;
        polar answer;
        answer.distance=sqrt(xypos.x*xypos.x+xypos.y*xypos.y);
        answer.angle=atan2(xypos.y,xypos.x);//y/x计算arctan
        return answer;//返回结构
    }
    
    void show_polar(polar dapos)
    {
        using namespace std;
        const double Rad_to_deg=57.29577951;//弧度转换为度数的常数因子
        cout<<"Distance = "<<dapos.distance;
        cout<<",angle = "<<dapos.angle*Rad_to_deg;
        cout<<" degrees\n";
    }
    
    //P9.4
    #include <iostream>
    void oil(int x);
    
    int main()
    {
        using namespace std;
    
        int texas=31;
        int year=2011;
        cout<<"In main(),texas= "<<texas<<",&texas= "<<&texas<<endl;
        cout<<"In main(),year= "<<year<<",&tear= "<<&year<<endl;
        oil(texas);
        cout<<"In main(),texas= "<<texas<<",&texas= "<<&texas<<endl;
        cout<<"In main(),year= "<<year<<",&tear= "<<&year<<endl;
        return 0;
    }
    
    void oil(int x)
    {
        using namespace std;
        int texas=5;
        cout<<"In oil(),texas= "<<texas<<",&texas= "<<&texas<<endl;
        cout<<"In oil(),x= "<<x<<",&x= "<<&x<<endl;
        {
            int texas=113;
            cout<<"In block,texas= "<<texas<<",&texas= "<<&texas<<endl;
            cout<<"In block,x= "<<x<<",&x= "<<&x<<endl;
        }//代码块内新定义暂时隐藏以前的定义
        cout<<"Post-block texas="<<texas<<",&texas= "<<&texas<<endl;
    }
    
    //P9.5-P9.6
    Main.cpp
    #include <iostream>
    
    double warming=0.3;//外部变量定义和初始化
    void update(double dt);
    void local();
    
    using namespace std;
    
    int main()
    {
        cout<<"Global warming is "<<warming<<" degrees.\n";
        update(0.1);
        cout<<"Global warming is "<<warming<<" degrees.\n";
        local();
        cout<<"Global warming is "<<warming<<" degrees.\n";
        return 0;
    }
    
    SubFunctions.cpp
    #include <iostream>
    
    extern double warming;//引用外部变量声明
    void update(double dt);
    void local();
    
    using std::cout;
    
    void update(double dt)
    {
        extern double warming;//引用外部变量变量
        warming+=dt;//修改外部变量
        cout<<"Updating global warming to "<<warming<<" degrees.\n";
    }
    
    void local()
    {
        double warming=0.8;
        cout<<"Local warming = "<<warming<<" degrees.\n";
        cout<<"But global warming = "<<::warming<<" degrees.\n";//作用域解析::访问全局变量
    }
    
    //P9.7-P9.8
    Main.cpp
    #include <iostream>
    void remote_access();
    
    int tom=3;//外部声明
    int dick=30;//外部声明
    static int harry=300;//内部声明
    
    int main()
    {
        using namespace std;
        cout<<"main() reports the following addresses:\n";
        cout<<&tom<<" = &tom, "<<&dick<<" = &dick, "<<&harry<<" = &harry\n";
        remote_access();
        return 0;
    }
    
    SubFunctions.cpp
    #include <iostream>
    
    extern int tom;//外部引用
    static int dick=10;//内部声明
    int harry=200;//外部声明
    
    void remote_access()
    {
        using namespace std;
        cout<<"remote_access() reports the following addresses:\n";
        cout<<&tom<<" = &tom, "<<&dick<<" = &dick, "<<&harry<<" = &harry\n";
    }
    
    //P9.9
    #include <iostream>
    const int ArSize=15;
    void strcount(const char* str);
    
    int main()
    {
        using namespace std;
        char input[ArSize];
        char next;
    
        cout<<"Enter a line:\n";
        cin.get(input,ArSize);
        while (cin)
        {
            cin.get(next);//读取回车
            while (next!='\n')//检查是否读取了回车确定是否有字符未被读取
                cin.get(next);//丢弃过多的字符
            strcount(input);//计算字符数的函数
            cout<<"Enter next line(empty line to quit):\n";
            cin.get(input,ArSize);
        }
        cout<<"Bye.\n";
        return 0;
    }
    
    void strcount(const char* str)
    {
        using namespace std;
        static int total=0;//每次调用仅第一次才初始化
        int count=0;//参照对象
    
        cout<<"\""<<str<<"\" contains ";
        while (*str++)//*str将获取数组第一个元素也就是第一个字母
            count++;//计算字符串里有多少字符
        total+=count;
        cout<<count<<" characters\n";
        cout<<total<<" characters total.\n";
    }
    
    //P9.10
    #include <iostream>
    //#include <new>
    const int BUF=512;
    const int N=5;
    char buffer[BUF];
    
    int main()
    {
        using namespace std;
        double *pd1,*pd2;//十分小心!此处易写成double* pd1,pd2;
        int i;
        cout<<"Calling new and placement new:\n";
        pd1=new double[N];
        pd2=new (buffer) double[N];
        for (i=0;i<N;i++)
            pd2[i]=pd1[i]=1000+20.0*i;
        cout<<"Memory addresses:\n"<<" heap: "<<pd1<<" static: "<<(void*)buffer<<endl;
        //此处(void*)强制类型转换成空类型是为了输出地址,因为p1是double指针,buffer是char指针
        cout<<"Memory contents:\n";
        for (i=0;i<N;i++)
        {
            cout<<pd1[i]<<" at "<<&pd1[i]<<"; ";
            cout<<pd2[i]<<" at "<<&pd2[i]<<endl;
        }
    
        cout<<"\nCalling new and palcement new a second time:\n";
        double* pd3,* pd4;
        pd3=new double[N];
        pd4=new (buffer) double[N];//将依然使用之前的地址
        for (i=0;i<N;i++)
            pd4[i]=pd3[i]=1000+40.0*i;
        cout<<"Memory contents:\n";
        for (i=0;i<N;i++)
        {
            cout<<pd3[i]<<" at "<<&pd3[i]<<"; ";
            cout<<pd4[i]<<" at "<<&pd4[i]<<endl;
        }
        cout<<"\nCalling new and palcement new a third time:\n";
        delete pd1;
        pd1=new double[N];
        pd2=new (buffer+N* sizeof(double)) double[N];//提供了5*8bytes的起始偏移量,地址改变
        for (i=0;i<N;i++)
            pd2[i]=pd1[i]=1000+60.0*i;
        cout<<"Memory contents:\n";
        for (i=0;i<N;i++)
        {
            cout<<pd1[i]<<" at "<<&pd1[i]<<"; ";
            cout<<pd2[i]<<" at "<<&pd2[i]<<endl;
        }
        delete [] pd1;
        delete [] pd3;
        //不释放pd2和pd4是因为它们并非指向堆的new出的内存,而是定位new
        return 0;
    }
    
    //P9.11-P9.13
    Z_Head.h
    #ifndef CLION_VERSION_Z_HEAD_H
    #define CLION_VERSION_Z_HEAD_H
    #include <string>
    
    namespace pers
    {
        struct Person
        {
            std::string fname;
            std::string lname;
        };
        void getPerson(Person&);
        void showPerson(const Person&);
    }
    
    namespace debts
    {
        using namespace pers;
        struct Debt
        {
            Person name;
            double amount;
        };
        void getDebt(Debt&);
        void showDebt(const Debt&);
        double sumDebts(const Debt ar[],int n);
    }
    #endif
    
    Main.cpp
    #include <iostream>
    #include "Z_Head.h"
    void other(void);
    void another(void);
    
    int main()
    {
        using debts::Debt;
        using debts::showDebt;
    
        Debt golf {{"Benny","Goatsniff"},120.0};
        showDebt(golf);
        other();
        another();
        return 0;
    }
    
    void other(void)
    {
        using std::cout;
        using std::endl;
        using namespace debts;
        Person dg {"Doodles","Glister"};
        showPerson(dg);//倒着先last后first输出名字
        cout<<endl;
        Debt zippy[3];//结构数组
        int i;
        for (i=0;i<3;i++)
            getDebt(zippy[i]);//姓名和钱款同时获取
        for (i=0;i<3;i++)
            showDebt(zippy[i]);//将输入全部输出显示
        cout<<"Total debt: $"<<sumDebts(zippy,3)<<endl;
        return;//无返回值
    }
    
    void another(void)
    {
        using pers::Person;
        Person collector {"Milo","Rightshift"};
        pers::showPerson(collector);
        std::cout<<std::endl;
    }
    
    SubFunctions.cpp
    #include <iostream>
    #include "Z_Head.h"
    namespace pers
    {
        using std::cout;
        using std::cin;
        void getPerson(Person& rp)
        {
            cout<<"Enter first name: ";
            cin>>rp.fname;
            cout<<"Enter last name: ";
            cin>>rp.lname;
        }
        void showPerson(const Person& rp)
        {
            std::cout<<rp.lname<<", "<<rp.fname;
        }
    }
    
    namespace debts
    {
        void getDebt(Debt& rd)
        {
            getPerson(rd.name);
            std::cout<<"Enter debt: ";
            std::cin>>rd.amount;
        }
        void showDebt(const Debt& rd)
        {
            showPerson(rd.name);//注意此函数位于pers空间且参数使用子成员.name
            std::cout<<": $"<<rd.amount<<std::endl;
        }
        double sumDebts(const Debt ar[],int n)
        {
            double total=0;
            for (int i=0;i<n;i++)
                total+=ar[i].amount;
            return total;
        }
    }
    
    //PP9.6.1
    Z_Head.h
    #ifndef CLION_VERSION_Z_HEAD_H
    #define CLION_VERSION_Z_HEAD_H
    
    const int Len=40;
    const int Num=3;
    struct golf
    {
        char fullname[Len];
        int hangdicap;
    };
    
    void setgolf(golf& g,const char* name,int hc);
    int setgolf(golf& g);
    
    void handicap(golf& g,int hc);
    void showgolf(const golf& g);
    
    #endif
    
    Main.cpp
    #include <iostream>
    #include "Z_Head.h"
    
    int main()
    {
        using namespace std;
        golf ZhangHu[Num];
        int i;
        for (i=0;i<Num;i++)
        {
            int NMX=setgolf(ZhangHu[i]);
            if (NMX==0)
                break;
        }
        if (i!=0)
        {
            for (int j=0;j<Num;j++)
            {
                cout<<"NO. "<<j+1<<": "<<endl;
                showgolf(ZhangHu[j]);
            }
        }
    
        golf ann;
        setgolf(ann,"Something is perfect!",66);
        cout<<endl;
        showgolf(ann);
        cout<<endl;
        handicap(ann,99);
        showgolf(ann);
        return 0;
    }
    
    SubFunctions.cpp
    #include <iostream>
    #include "Z_Head.h"
    
    using namespace std;
    void setgolf(golf& g,const char* name,int hc)
    {
        strcpy(g.fullname,name);
        g.hangdicap=hc;
    }
    
    int setgolf(golf& g)
    {
        cout<<"Please enter a name: ";
        cin.get(g.fullname,Len);
        if (g.fullname[0]=='\0')
            return 0;
        cout<<"Please enter a rank: ";
        while (!(cin>>g.hangdicap))//注意输入被置于条件内!
        {
            cin.clear();
            while (cin.get()!='\n')
                continue;
            cout<<"Try again!"<<endl;
        }
        cin.get();
        return 1;
    }
    
    void handicap(golf& g,int hc)
    {
        g.hangdicap=hc;
    }
    
    void showgolf(const golf& g)
    {
        cout<<"name: "<<g.fullname<<endl;
        cout<<"handicap: "<<g.hangdicap<<endl;
    }
    
    //PP9.6.2
    #include <iostream>
    void strcount(const std::string str);
    
    int main()
    {
        using namespace std;
        string input;
        char next;
    
        cout<<"Enter a line:\n";
        getline(cin,input);
        while (input!="")
        {
            strcount(input);//计算字符数的函数
            cout<<"Enter next line(empty line to quit):\n";
            getline(cin,input);
        }
        cout<<"Bye.\n";
        return 0;
    }
    
    void strcount(const std::string str)
    {
        using namespace std;
        static int total=0;//每次调用仅第一次才初始化
        int count=0;//参照对象
    
        cout<<"\""<<str<<"\" contains ";
        count=str.size();
        total+=count;
        cout<<count<<" characters\n";
        cout<<total<<" characters total.\n";
    }
    
    //PP9.6.3
    #include <iostream>
    const int BUF=512;
    char buffer[BUF];
    struct chaff
    {
        char dross[20];
        int slag;
    };
    int main()
    {
        using namespace std;
        chaff *ps1=new chaff[2];
        strcpy(ps1->dross,"EnochHugh");
        ps1->slag=5;
        strcpy((ps1+1)->dross,"YangHsuChou");
        (ps1+1)->slag=9;
        for (int i=0;i<2;i++,ps1++)
        {
            cout<<"ps1: Droos: "<<ps1->dross<<endl;
            cout<<"ps1: Slag: "<<ps1->slag<<endl;
        }
        cout<<endl;
        chaff *ps2=new (buffer) chaff[2];
        strcpy(ps2->dross,"EnochHugh");
        ps2->slag=5;
        strcpy((ps2+1)->dross,"YangHsuChou");
        (ps2+1)->slag=9;
        const chaff *end=ps2+2;//强行使用指针循环
        for (;ps2<end;ps2++)
        {
            cout<<"ps2: Droos: "<<ps2->dross<<endl;
            cout<<"ps2: Slag: "<<ps2->slag<<endl;
        }
    
        delete (ps1-2);
        return 0;
    }
    
    //PP9.6.4
    Z_Head.h
    #ifndef CLION_VERSION_Z_HEAD_H
    #define CLION_VERSION_Z_HEAD_H
    
    namespace SALES
    {
        const int QUARTERS=4;
        struct Sales
        {
            double sales[QUARTERS];
            double average;
            double max;
            double min;
        };
        void setSales(Sales& s,const double ar[],int n);
        void setSales(Sales& s);
        void showSales(const Sales& s);
        double findMax(double ar[],int ARSZ);
        double findMin(double ar[],int ARSZ);
    }
    
    #endif
    
    Main.cpp
    #include <iostream>
    #include "Z_Head.h"
    
    int main()
    {
        const double price[SALES::QUARTERS] {12.34,34.54,66.99,99.123};
        int ZHS=10;
        SALES::Sales* xv=new SALES::Sales[2];
        SALES::setSales(*xv,price,ZHS);
        SALES::showSales(*xv);
        SALES::setSales(*(xv+1));
        SALES::showSales(*(xv+1));
        delete xv;
        return 0;
    }
    
    SubFunctions.cpp
    #include <iostream>
    #include "Z_Head.h"
    
    namespace SALES
    {
        void setSales(Sales& s,const double ar[],int n)
        {
            int realv=(QUARTERS>n?n:QUARTERS);
            double total=0;
            for (int i=0;i<realv;i++)
            {
                s.sales[i]=ar[i];
                total+=ar[i];
            }
            s.average=total/realv;
            s.max=findMax(s.sales,realv);
            s.min=findMin(s.sales,realv);
    
        }
    
        void setSales(Sales& s)
        {
            using std::cin;
            using std::cout;
            using std::endl;
            cout<<"Please enter the number: "<<endl;
            double total=0;
            for (int i=0;i<QUARTERS;i++)
            {
                cin>>s.sales[i];
                if (!cin)
                {
                    cin.clear();
                    while (cin.get()!='\n')
                        continue;
                }
                total+=s.sales[i];
                s.average=total/QUARTERS;
                s.max=findMax(s.sales,QUARTERS);
                s.min=findMin(s.sales,QUARTERS);
            }
        }
    
        void showSales(const Sales& s)
        {
            using std::cout;
            using std::endl;
            cout<<"*xv sales:";
            for (int i=0;i<QUARTERS;i++)
                cout<<s.sales[i]<<" ";
            cout<<endl;
            cout<<"*xv average:"<<s.average<<endl;
            cout<<"*xv max:"<<s.max<<endl;
            cout<<"*xv min:"<<s.min<<endl;
        }
    
        double findMax(double ar[],int ARSZ)
        {
            double max=ar[0];
            for (int i=1;i<ARSZ;i++)
            {
                if (ar[i]>max)
                    max=ar[i];
            }
            return max;
        }
    
        double findMin(double ar[],int ARSZ)
        {
            double min=ar[0];
            for (int i=1;i<ARSZ;i++)
            {
                if (ar[i]<min)
                    min=ar[i];
            }
            return min;
        }
    }
    

    相关文章

      网友评论

          本文标题:CPP_Basic_Code_P9.1-PP9.6.4

          本文链接:https://www.haomeiwen.com/subject/kgdktxtx.html