CPP_Basic_Code_P9.1-PP9.6.4

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,383评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,522评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,852评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,621评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,741评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,929评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,076评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,803评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,265评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,582评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,716评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,395评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,039评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,027评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,488评论 2 361
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,612评论 2 350

推荐阅读更多精彩内容