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})//可使用指定源文件引入可執(zhí)行文件

coordin.h
#ifndef CLION_VERSION_COORDIN_H
#define CLION_VERSION_COORDIN_H

struct polar//極坐標(biāo)結(jié)構(gòu)
{
    double distance;
    double angle;
};
struct rect//直角坐標(biāo)結(jié)構(gòu)
{
    double x;
    double y;
};

polar rect_to_polar(rect xypos);//直角轉(zhuǎn)為極坐標(biāo)
void show_polar(polar dapos);//顯示極坐標(biāo)

#endif //CLION_VERSION_COORDIN_H

file1.cpp
#include <iostream>
#include "coordin.h"

int main()
{
    using namespace std;
    rect rplace;//聲明兩個(gè)結(jié)構(gòu)以存儲輸入的數(shù)據(jù)
    polar pplace;

    cout<<"Enter the x and y value: ";
    while (cin>>rplace.x>>rplace.y)//連續(xù)使用cin可行,且忽略空格等
    {
        pplace=rect_to_polar(rplace);//結(jié)果賦值給第二個(gè)結(jié)構(gòu)
        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計(jì)算arctan
    return answer;//返回結(jié)構(gòu)
}

void show_polar(polar dapos)
{
    using namespace std;
    const double Rad_to_deg=57.29577951;//弧度轉(zhuǎn)換為度數(shù)的常數(shù)因子
    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;
    }//代碼塊內(nèi)新定義暫時(shí)隱藏以前的定義
    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;//內(nèi)部聲明

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;//內(nèi)部聲明
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);//計(jì)算字符數(shù)的函數(shù)
        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;//每次調(diào)用僅第一次才初始化
    int count=0;//參照對象

    cout<<"\""<<str<<"\" contains ";
    while (*str++)//*str將獲取數(shù)組第一個(gè)元素也就是第一個(gè)字母
        count++;//計(jì)算字符串里有多少字符
    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*)強(qiáng)制類型轉(zhuǎn)換成空類型是為了輸出地址性置,因?yàn)閜1是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是因?yàn)樗鼈儾⒎侵赶蚨训膎ew出的內(nèi)存,而是定位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];//結(jié)構(gòu)數(shù)組
    int i;
    for (i=0;i<3;i++)
        getDebt(zippy[i]);//姓名和錢款同時(shí)獲取
    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);//注意此函數(shù)位于pers空間且參數(shù)使用子成員.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))//注意輸入被置于條件內(nèi)!
    {
        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);//計(jì)算字符數(shù)的函數(shù)
        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;//每次調(diào)用僅第一次才初始化
    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;//強(qiáng)行使用指針循環(huán)
    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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末扣汪,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子伟叛,更是在濱河造成了極大的恐慌私痹,老刑警劉巖,帶你破解...
    沈念sama閱讀 223,126評論 6 520
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件统刮,死亡現(xiàn)場離奇詭異紊遵,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)侥蒙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,421評論 3 400
  • 文/潘曉璐 我一進(jìn)店門暗膜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人鞭衩,你說我怎么就攤上這事学搜⊥奚疲” “怎么了?”我有些...
    開封第一講書人閱讀 169,941評論 0 366
  • 文/不壞的土叔 我叫張陵瑞佩,是天一觀的道長聚磺。 經(jīng)常有香客問我,道長炬丸,這世上最難降的妖魔是什么瘫寝? 我笑而不...
    開封第一講書人閱讀 60,294評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮稠炬,結(jié)果婚禮上焕阿,老公的妹妹穿的比我還像新娘。我一直安慰自己首启,他們只是感情好暮屡,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,295評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著毅桃,像睡著了一般褒纲。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上疾嗅,一...
    開封第一講書人閱讀 52,874評論 1 314
  • 那天外厂,我揣著相機(jī)與錄音,去河邊找鬼代承。 笑死,一個(gè)胖子當(dāng)著我的面吹牛渐扮,可吹牛的內(nèi)容都是我干的论悴。 我是一名探鬼主播,決...
    沈念sama閱讀 41,285評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼墓律,長吁一口氣:“原來是場噩夢啊……” “哼膀估!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起耻讽,我...
    開封第一講書人閱讀 40,249評論 0 277
  • 序言:老撾萬榮一對情侶失蹤察纯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后针肥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體饼记,經(jīng)...
    沈念sama閱讀 46,760評論 1 321
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,840評論 3 343
  • 正文 我和宋清朗相戀三年慰枕,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了具则。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,973評論 1 354
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡具帮,死狀恐怖博肋,靈堂內(nèi)的尸體忽然破棺而出低斋,到底是詐尸還是另有隱情,我是刑警寧澤匪凡,帶...
    沈念sama閱讀 36,631評論 5 351
  • 正文 年R本政府宣布膊畴,位于F島的核電站,受9級特大地震影響病游,放射性物質(zhì)發(fā)生泄漏唇跨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,315評論 3 336
  • 文/蒙蒙 一礁遵、第九天 我趴在偏房一處隱蔽的房頂上張望轻绞。 院中可真熱鬧,春花似錦佣耐、人聲如沸政勃。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,797評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽奸远。三九已至,卻和暖如春讽挟,著一層夾襖步出監(jiān)牢的瞬間懒叛,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,926評論 1 275
  • 我被黑心中介騙來泰國打工耽梅, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留薛窥,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,431評論 3 379
  • 正文 我出身青樓眼姐,卻偏偏與公主長得像诅迷,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子众旗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,982評論 2 361

推薦閱讀更多精彩內(nèi)容