CPP_Basic_Code_P7.1-PP7.13.10

版权声明:本文虽为 贴墙上的咖啡 原创,未经允许仍可转载. https://blog.csdn.net/enochhugh/article/details/70144309

##CPP_Basic_Code_P7.1-PP7.13.10

//  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

//P7.1
#include <iostream>
void simple();//声明没有返回值的函数
int main()
{
    using namespace std;
    cout<<"main() will call the function simple(): \n";
    simple();
    cout<<"main() is finisied with the simple() function.\n";
    //cin.get();
    return 0;
}

void simple()//具体的函数编写
{
    using namespace std;
    cout<<"I'm but s simple function.\n";
}

//P7.2
#include <iostream>
void cheers(int);
double cube(double x);//有返回值的函数
int main()
{
    using namespace std;
    cheers(5);
    cout<<"Give me a number:\n";
    double side;
    cin>>side;
    double volume=cube(side);
    cout<<"A "<<side<<"-foot cube has a volume of ";
    cout<<volume<<" cubic feet.\n";
    cheers(cube(2));//2的立方为8
    return 0;
}

void cheers(int n)
{
    using namespace std;
    for (int i=0;i<n;i++)
        cout<<"cheers! ";
    cout<<endl;
}

double cube(double x)
{
    return x*x*x;
}                                                                                                  

//P7.3
#include <iostream>
using namespace std;
void n_chars(char,int);
int main()
{
    int times;
    char ch;
    cout<<"Enter a character: ";
    cin>>ch;
    while (ch!='q')//输入'q'则退出程序
    {
        cout<<"Enter an integer: ";
        cin>>times;
        n_chars(ch,times);//注意调用方式
        cout<<"\nEnter another character or press the q-Key to quit: ";
        cin>>ch;
    }
    cout<<"The value of times is "<<times<<".\n";
    cout<<"Bye\n";
    return 0;
}

void n_chars(char c,int n)//子函数全部使用内部的局部变量
{
    while (n-- >0)
        cout<<c;
}

//P7.4
#include <iostream>
long double probability(unsigned numbers,unsigned picks);
int main()
{
    using namespace std;
    double total,choices;
    cout<<"Enter the number of choices on the game card and\n"
        "the number of picks allowed:\n";
    while ((cin>>total>>choices)&&choices<=total)
    {
        cout<<"You have one chance in ";
        cout<<probability(total,choices);
        cout<<" of winning.\n";
        cout<<"Next two numbers (q to quit): ";
    }
    cout<<"Bye\n";
    return 0;
}

long double probability(unsigned numbers,unsigned picks)//形参
{
    long double result=1.0;
    long double n;//提前定义局部变量
    unsigned p;
    for (n=numbers,p=picks;p>0;n--,p--)
        result=result*n/p;//利用连乘实现计算且避免中间数过大
    return result;//返回结果
}

//P7.5
#include <iostream>
const int ArSize=8;
int sum_arr(int arr[],int n);//声明传递数组的函数,指针和整数
//此处也可使用int* arr来实现数组的声明
int main()
{
    using namespace std;
    int cookies[ArSize] {1,2,4,8,16,32,64,128};
    int sum=sum_arr(cookies,ArSize);//函数调用后赋值
    cout<<"Total cookies eaten: "<<sum<<"\n";
    return 0;
}

int sum_arr(int arr[],int n)
{
    int total=0;
    for (int i=0;i<n;i++)
        total=total+arr[i];//传递的指针可当做数组名使用
    return total;
}


//P7.6
#include <iostream>
const int ArSize=8;
int sum_arr(int arr[],int n);
int main()
{
    int cookies[ArSize] {1,2,4,8,16,32,64,128};
    std::cout<<cookies<<" = array address, ";//数组名输出将输出数组地址
    std::cout<<sizeof cookies<<" = sizeof cookies\n";//输出数组名大小将输出整个数组大小
    int sum=sum_arr(cookies,ArSize);//函数调用后赋值
    std::cout<<"Total cookies eaten: "<<sum<<std::endl;
    sum=sum_arr(cookies,3);//传递参数指出数组只有三个元素从而计算前三者总和
    std::cout<<"First three eaters ate "<<sum<<" cookies.\n";
    sum=sum_arr(cookies+4,4);//使用指针加减来移动指针位置到第五个元素,往后四个
    //此处也可以使用&cookies[4]来取代cookies+4,效果一样
    std::cout<<"Last four eaters ate "<<sum<<" cookies.\n";
    return 0;
}

int sum_arr(int arr[],int n)
{
    int total=0;
    std::cout<<arr<<" = arr, ";//输出指针(数组名)地址
    std::cout<<sizeof arr<<" = sizeof arr\n";//输出指针长度
    for (int i=0;i<n;i++)
        total=total+arr[i];//传递的指针可当做数组名使用
    return total;
}

//P7.7
#include <iostream>
const int Max =5;
int fill_array(double ar[],int limit);//填充数组函数,返回输入的个数
void show_array(const double ar[],int n);//打印函数,无返回值
void revalue(double r,double ar[],int n);//修改数组函数,直接修改数组无返回值

int main()
{
    using namespace std;
    double properties[Max];//定义一个数组记录财产

    int size=fill_array(properties,Max);//将实际输出的元素数赋值到size
    show_array(properties,size);//打印size个财产
    if (size>0)
    {
        cout<<"Enter revaluation factor: ";
        double factor;//输入重新评估因子用于修改数组中的值
        while (!(cin>>factor))//输入失败检测模块
        {
            cin.clear();
            while (cin.get()!='\n')
                continue;
            cout<<"Bad input;please enter a number: ";
        }
        revalue(factor,properties,size);//调用修改数组函数
        show_array(properties,size);//显示修改后的数组函数
    }
    cout<<"Done.\n";
    cin.get();//光标浮动以等待输入
    cin.get();
    return 0;
}

int fill_array(double ar[],int limit)
{
    using namespace std;
    double temp;
    int i;
    for (i=0;i<limit;i++)
    {
        cout<<"Enter value#"<<(i+1)<<": ";
        cin>>temp;//读取并写入数组
        if (!cin)//输入失败检测模块
        {
            cin.clear();
            while (cin.get()!='\n')
                continue;
            cout<<"Bad input;input  process terminated.\n";
            break;
        }
        else if (temp<0)//输入负数跳出读取
            break;
        ar[i]=temp;//如果非负则赋值成功
    }
    return i;
}

void show_array(const double ar[],int n)
{
    using namespace std;
    for (int i=0;i<n;i++)
    {
        cout<<"Property #"<<(i+1)<<": $";//循环打印数组
        cout<<ar[i]<<endl;
    }
}

void revalue(double r,double ar[],int n)
{
    for (int i=0;i<n;i++)
        ar[i]*=r;//和修改因子相乘后重新赋值
}


//P7.8
#include <iostream>
const int ArSize=8;
int sum_arr(const int * begin,const int * end);//定义数组区别函数,用指针区间传递参数
int main()
{
    using namespace std;
    int cookies[ArSize] {1,2,4,8,16,32,64,128};
    int sum=sum_arr(cookies,cookies+ArSize);//区间为1~ArSize
    cout<<"Total cookies eaten: "<<sum<<endl;
    sum=sum_arr(cookies,cookies+3);//传递参数指出数组只有三个元素从而计算前三者总和
    cout<<"First three eaters ate "<<sum<<" cookies.\n";
    sum=sum_arr(cookies+4,cookies+8);//使用指针区间指定后四个元素
    cout<<"Last four eaters ate "<<sum<<" cookies.\n";
    return 0;
}

int sum_arr(const int * begin,const int * end)
{
    const int * pt;
    int total=0;
    for (pt=begin;pt!=end;pt++)//end为最后一个元素的后面一个位置
        total+=*pt;
    return total;
}

//P7.9
#include <iostream>
unsigned int c_in_str(const char* str,char ch);//也可使用const char str[]
int main()
{
    using namespace std;
    char mmm[15]="minimum";

    char* wail="ululate";//显式指针赋值

    unsigned int ms=c_in_str(mmm,'m');//指针参数和特征字符参数
    unsigned int us=c_in_str(wail,'u');
    cout<<ms<<" m characters in "<<mmm<<endl;
    cout<<us<<" u characters in "<<wail<<endl;
    return 0;
}

unsigned int c_in_str(const char* str,char ch)
{
    unsigned int count=0;

    while (*str)//*str表示的第一个字符,不为空值符就继续循环直到'\0'
    {
        if (*str==ch)
            count++;
        str++;//移动指针继续指向下一个字符
    }
    return count;
}


//P7.10
#include <iostream>
char* buildstr(char c,int n);//返回指针的函数声明
int main()
{
    using namespace std;
    int times;
    char ch;

    cout<<"Enter a character: ";
    cin>>ch;
    cout<<"Enter a integer: ";
    cin>>times;
    char* ps=buildstr(ch,times);
    cout<<ps<<endl;
    delete [] ps;//释放子函数new出的char*指针
    ps=buildstr('+',20);
    cout<<ps<<"-DONE-"<<ps<<endl;
    delete [] ps;
    return 0;
}

char* buildstr(char c,int n)
{
    char* pstr=new char[n+1];//创建指针指向次数+1,因为结尾是'\0'
    pstr[n]='\0';//设置结尾
    while (n-->0)//n减到0
        pstr[n]=c;//将字符c的值赋值给数组中各元素位置
    return pstr;//返回字符串指针,new出来的地址
}


//P7.11
#include <iostream>
struct travel_time
{
    int hours;
    int mins;
};
const int Mins_per_hr=60;//1小时=60分

travel_time sum(travel_time t1,travel_time t2);//返回结构的函数原型声明,接收2个结构参数
void show_time(travel_time t);//显示结构,接收1个结构参数

int main()
{
    using namespace std;
    travel_time day1={5,45};//注意结构不用()用{}
    travel_time day2={4,55};

    travel_time trip=sum(day1,day2);//结构赋值
    cout<<"Two_day total: ";
    show_time(trip);

    travel_time day3={4,32};
    cout<<"Three-day total: ";
    show_time(sum(trip,day3));

    return 0;
}

travel_time sum(travel_time t1,travel_time t2)
{
    travel_time total;

    total.mins=(t1.mins+t2.mins)%Mins_per_hr;//取模获得剩余分钟数
    total.hours=t1.hours+t2.hours+(t1.mins+t2.mins)/Mins_per_hr;//除法获得小时数

    return total;
}

void show_time(travel_time t)
{
    using namespace std;
    cout<<t.hours<<" hours, "
                 <<t.mins<<" minutes\n";
}

//P7.12
#include <iostream>
#include <cmath>

struct polar//极坐标结构
{
    double distance;
    double angle;
};
struct rect//直角坐标结构
{
    double x;
    double y;
};

polar rect_to_polar(rect xypos);//直角转为极坐标
void show_polar(polar dapos);//显示极坐标
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;
}

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";
}

//P7.13
#include <iostream>
#include <cmath>

struct polar//极坐标结构
{
    double distance;
    double angle;
};
struct rect//直角坐标结构
{
    double x;
    double y;
};

void rect_to_polar(const rect* pxy,polar* pda);//传递指针,第二个需要修改故不const
void show_polar(const polar* pda);//显示极坐标
int main()
{
    using namespace std;
    rect rplace;//声明两个结构以存储输入的数据
    polar pplace;

    cout<<"Enter the x and y value: ";
    while (cin>>rplace.x>>rplace.y)//连续使用cin可行,且忽略空格等
    {
        rect_to_polar(&rplace,&pplace);//结果赋值给第二个结构
        show_polar(&pplace);//显示
        cout<<"Next two numbers (q to quiit): ";
    }
    cout<<"Done.\n";
    return 0;
}

void rect_to_polar(const rect* pxy,polar* pda)
{
    using namespace std;
    pda->distance=sqrt(pxy->x*pxy->x+pxy->y*pxy->y);//指针使用->来控制成员
    pda->angle=atan2(pxy->y,pxy->x);
}

void show_polar(const polar* pda)
{
    using namespace std;
    const double Rad_to_deg=57.29577951;//弧度转换为度数的常数因子
    cout<<"Distance = "<<pda->distance;
    cout<<",angle = "<<pda->angle*Rad_to_deg;
    cout<<" degrees\n";
}


//P7.14
#include <iostream>
#include <string>
using namespace std;
const int SIZE=5;
void display(const string sa[],int n);//可写为string* sa
int main()
{
    string list[SIZE];
    cout<<"Enter your "<<SIZE<<"favorite astronomical sights: \n";
    for (int i=0;i<SIZE;i++)
    {
        cout<<i+1<<": ";
        getline(cin,list[i]);//抽取整行
    }
    cout<<"Your list:\n";
    display(list,SIZE);//调用显示模块

    return 0;
}

void display(const string sa[],int n)//传递数组指针和容量参数n
{
    for (int i=0;i<n;i++)
        cout<<i+1<<": "<<sa[i]<<endl;
}

//P7.15
#include <iostream>
#include <array>
#include <string>

const int Seasons=4;
const std::array<std::string,Seasons> Snames=
        {"Spring","Summer","Fall","Winter"};
void fill(std::array<double,Seasons> *pa);
void show(std::array<double,Seasons> da);

int main()
{
    std::array<double,Seasons> expenses;
    fill(&expenses);//传递地址指针效率高但是看起来复杂
    show(expenses);//传递实体效率低下
    return 0;
}

void fill(std::array<double,Seasons> *pa)
{
    using namespace std;
    for (int i=0;i<Seasons;i++)
    {
        cout<<"Enter "<<Snames[i]<<" expenses: ";
        cin>>(*pa)[i];//此处括号必不可少
    }
}

void show(std::array<double,Seasons> da)
{
    using namespace std;
    double total=0.0;
    cout<<"\nEXPENSES\n";
    for (int i=0;i<Seasons;i++)
    {
        cout<<Snames[i]<<": $"<<da[i]<<endl;
        total+=da[i];//求和
    }
    cout<<"Total Expenses: $"<<total<<endl;
}

//P7.16
#include <iostream>
void countdown(int n);
int main()
{
    countdown(4);
    return 0;
}

void countdown(int n)
{
    using namespace std;
    cout<<"Counting down……"<<n<<" n at "<<&n<<endl;
    if (n>0)
        countdown(n-1);//递归递减
    cout<<n<<":Kaboom!"<<" n at "<<&n<<endl;//逆向退出程序队列故反向输出
}

//P7.17
#include <iostream>
const int Len=66;
const int Divs=6;
void subdivide(char ar[],int low,int high,int level);
int main()
{
    char ruler[Len];
    int i;
    for (i=1;i<Len-2;i++)
        ruler[i]=' ';//中间元素全部填充空格
    ruler[Len-1]='\0';//结尾处填充结束的\0
    int max=Len-2;//数组\0前的最后一个元素
    int min=0;//数组第一个元素
    ruler[min]=ruler[max]='|';//首尾填充|
    std::cout<<ruler<<std::endl;
    for (i=1;i<=Divs;i++)//一下循环ivs次
    {
        subdivide(ruler,min,max,i);
        std::cout<<ruler<<std::endl;
        for (int j=1;j<Len-2;j++)
            ruler[j]=' ';//每次均重新填充空格再继续下一次循环
    }
    return 0;
}

void subdivide(char ar[],int low,int high,int level)
{
    if (0==level)
        return;//返回到主函数处继续执行
    int mid=(high+low)/2;//求出中间元素的位置数
    ar[mid]='|';//将中间这个位置填充|
    subdivide(ar,low,mid,level-1);//继续调用递归,但是level-1
    subdivide(ar,mid,high,level-1);//后半部分同理
}

//P7.18
#include <iostream>
double betsy(int);
double pam(int);
void estimate(int lines,double (*pf)(int));//声明了函数指针
//(*pf)等同函数名效果,两者用法一致;且因历史原因,pf等价于(*pf)
int main()
{
    using namespace std;
    int code;
    cout<<"How many lines of code do you need? ";
    cin>>code;
    cout<<"Here's Betsy's estimate:\n";
    estimate(code,betsy);//调用函数指针betsy,函数名即地址,可传递
    cout<<"Here's Pam's estimate:\n";
    estimate(code,pam);
    return 0;
}

void estimate(int lines,double (*pf)(int))
{
    using namespace std;
    cout<<lines<<" lines will take ";
    cout<<(*pf)(lines)<<" hour(s)\n";//函数指针调用来计算line
}

double betsy(int lns)
{
    return 0.05*lns;
}

double pam(int lns)
{
    return 0.03*lns+0.0004*lns*lns;
}

//P7.19 R
#include <iostream>
const double* f1(const double ar[],int n);
const double* f2(const double [],int n);
const double* f3(const double *,int n);
//以上3种函数声明是完全相同的效果
int main()
{
    using namespace std;
    double av[3] {1112.3,1542.6,2227.9};

    const double *(*p1) (const double *,int)=f1;//定义函数指针p1,初始化指向f1
    auto p2=f2;//自动推导来自定义初始化p2,指向f2

    cout<<"Using pointers to functions:\n";
    cout<<"Address Value\n";
    cout<<(*p1)(av,3)<<": "<<*(*p1)(av,3)<<endl;
    //第一个函数调用返回double*地址,第二个解除引用将返回指向的具体double值
    cout<<p2(av,3)<<": "<<*p2(av,3)<<endl;
    //p2和(*p2)在函数调用时是完全等价的(C++规定),解除只需同样左加*即可
    const double *(*pa[3])(const double *,int) {f1,f2,f3};
    //pa是一个数组,它的元素是指针,且这些指针是函数指针,分别指向f1,f2,f3
    //这些函数指针的返回类型是double*
    auto pb=pa;//声明同样类型的数组

    cout<<"\nUsing an array of pointers to function:\n";
    cout<<"Address Value\n";
    for (int i=0;i<3;i++)
        cout<<pa[i](av,3)<<": "<<*pa[i](av,3)<<endl;
    cout<<"\nUsing a pointer to pointer to a funtion:\n";
    cout<<"Address Value\n";
    for (int i=0;i<3;i++)
        cout<<pb[i](av,3)<<": "<<*pb[i](av,3)<<endl;
    cout<<"\nUsing pointer to an array of pointers:\n";
    cout<<"Address Value\n";
    auto pc=&pa;//指向整个数组的指针,也就是指向数组指针的指针

    cout<<(*pc)[0](av,3)<<": "<<*(*pc)[0](av,3)<<endl;
    const double *(*(*pd)[3])(const double *,int)=&pa;
    //pd是一个指针,且是一个指向数组的指针
    //而数组的元素也是指针,且是函数指针,返回double*
    const double * pdb=(*pd)[1](av,3);//pd是pa的地址,故(*pd)就是数组名
    cout<<pdb<<": "<<*pdb<<endl;//前者是函数返回的地址,后者是函数的实际返回值
    cout<<(*(*pd)[2])(av,3)<<": "<<*(*(*pd)[2])(av,3)<<endl;
    //数组元素(*pd)[2]是一个函数指针,解除引用后是函数调用,返回地址
    //后者再次解除引用就获得函数实际返回值
    return 0;
}

const double* f1(const double ar[],int n)
{
    return ar;
}

const double* f2(const double ar[],int n)
{
    return ar+1;//指针右移到下1个数组元素
}

const double* f3(const double ar[],int n)
{
    return ar+2;//指针右移到下2个数组元素
}


//PP7.13.1
#include <iostream>
void show();
double thpjs(double x,double y);
double n1,n2;
int main()
{
    using namespace std;
    show();//调用函数不加前面的返回值类型
    while (n1!=0&&n2!=0)
    {
        double result=thpjs(n1,n2);
        cout<<"Result of your input: "<<result<<endl;
        show();
    }
    cout<<"wrong input!";
    return 0;
}

double thpjs(double x,double y)//计算函数
{
    return 2.0*x*y/(x+y);
}

void show()//读取数据
{
    using namespace std;
    cout<<"Please enter a number: ";
    cin>>n1;
    cout<<"Please enter another number: ";
    cin>>n2;
}

//PP7.13.2
#include <iostream>
int score_input(double *,int);
double score_average(const double *,int);
void score_show(const double *,int,double);//务必注意const必须全部到位!
const int ArSize=10;
int main()
{
    using namespace std;
    double score_list[ArSize] {0};//初始化成绩数组
    int realsize=score_input(score_list,ArSize);//获取数据同时返回实际输入的值
    double averagex=score_average(score_list,realsize);//调用函数获取数组平均值
    score_show(score_list,realsize,averagex);//显示函数
    return 0;
}

int score_input(double arr[],int limit)
{
    using namespace std;
    double temp=0;//输入安全检测临时变量
    int i;
    for (i=0;i<limit;i++)
    {
        cout<<"Please Enter score#"<<i+1<<": ";
        cin>>temp;
        if (!cin)//异常处理模块
        {
            cin.clear();
            while (cin.get()!='\n')//注意此处是cin.get()
                continue;
            cout<<"Bad input,over.\n";
            break;
        }
        if (temp<0)//输入无效跳出
            break;
        arr[i]=temp;//有效则赋值
    }
    return i;//返回实际输入的个数
}

double score_average(const double arr[],int limit)//注意const
{
    double sum=0;
    for (int i=0;i<limit;i++)
    {
        sum+=arr[i];
    }
    return sum/limit;
}

void score_show(const double arr[],int limit,double v)
{
    using namespace std;
    cout<<"Score list: ";
    for (int i=0;i<limit;i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<"\nAverage score: "<<v<<endl;
}


//PP7.13.3
#include <iostream>
const int ArSize=40;
struct box
{
    char maker[ArSize];
    float height;
    float width;
    float length;
    float volume;
};
box input_real_value(box rv);//按实值传递读取输入
box show_real_value(box rv);//按实值传递显示
void input_pointer(box* spr);//按指针传递读取输入
void show_pointer(const box* spr);//按指针传递显示

int main()
{
    using namespace std;
    box xv1;
    xv1=input_real_value(xv1);//读取数据到xv1
    show_real_value(xv1);//显示读入的数据
    box* xv2=new box;//指针指向new出的box结构
    input_pointer(xv2);//读取输入到指针指向的结构
    show_pointer(xv2);
    delete xv2;//勿忘
    return 0;
}

box input_real_value(box rv)
{
    using namespace std;
    cout<<"Please enter the maker:";
    cin>>rv.maker;
    cout<<"Please enter the height,width,length: ";
    cin>>rv.height>>rv.width>>rv.length;//数据可以连续读取
    rv.volume=rv.height*rv.width*rv.length;//体积计算
    return rv;
}

box show_real_value(box rv)
{
    using namespace std;
    cout<<"Maker: "<<rv.maker<<endl;
    cout<<"Height,width,length: "<<rv.height
        <<" "<<rv.width<<" "<<rv.length<<" "<<endl;
    cout<<"Volume: "<<rv.volume<<endl;
}

void input_pointer(box* spr)
{
    using namespace std;
    cout<<"Please enter the maker:";
    cin>>spr->maker;
    cout<<"Please enter the height,width,length: ";
    cin>>spr->height>>spr->width>>spr->length;//指针式连续读取
    spr->volume=spr->height*spr->width*spr->length;
}

void show_pointer(const box* spr)
{
    using namespace std;
    cout<<"Maker: "<<spr->maker<<endl;
    cout<<"Height,width,length: "<<spr->height
        <<" "<<spr->width<<" "<<spr->length<<" "<<endl;
    cout<<"Volume: "<<spr->volume<<endl;
}

//PP7.13.4
#include <iostream>
long double probability(unsigned field_numbers,unsigned picks,double extr);
int main()
{
    using namespace std;
    double total,choices,extra;
    long double pro;
    cout<<"Enter field_numbers,the number of picks allowed and extra_number:\n";
    cout<<"Of course,'q' to quit."<<endl;
    while ((cin>>total>>choices>>extra)&&choices<=total)
        //同时读取三个参数
    {
        pro=probability(total,choices,extra);
        cout<<"Input is ok.\n";
        break;
    }
    cout<<"Probability to win top-Money is: "<<pro<<endl;
    cout<<"Bye\n";
    return 0;
}

long double probability(unsigned field_numbers,unsigned picks,double extr)//形参
{
    long double result=1.0;
    long double n;//提前定义局部变量
    unsigned p;
    for (n=field_numbers,p=picks;p>0;n--,p--)
        result=result*n/p;//利用连乘实现计算且避免中间数过大
    result=result*(1/extr);
    return result;//返回结果
}

//PP7.13.5
#include <iostream>
long long int n_multiplication(int n);
int main()
{
    using namespace std;
    cout<<"Enter the number: (q to quit.)";
    int n_number;
    while (cin>>n_number)
    {
        long long int result=n_multiplication(n_number);
        cout<<n_number<<"!= "<<result<<endl;
        cout<<"Next number: ";
    }
    cout<<"Done.\n";
    return 0;
}

long long int n_multiplication(int n)
{
    using namespace std;
    long long int RST;
    if (n>0)
        RST=n*n_multiplication(n-1);//递归关键核心
    else
        RST=1;
    return RST;
}


//PP7.13.6
#include <iostream>
int Fill_array(double arr[],int limit);
void show_array(const double [],int limit);
void reverse_array(double *,int limit);
const int ArSize=10;
int main()
{
    using namespace std;
    double z_array[ArSize];
    int realvalue=Fill_array(z_array,ArSize);
    show_array(z_array,realvalue);

    reverse_array(z_array,realvalue);
    show_array(z_array,realvalue);

    reverse_array(z_array+1,realvalue-2);//指针右移一个元素以及长度缩短两个元素
    show_array(z_array,realvalue);
    return 0;
}

int Fill_array(double arr[],int limit)
{
    using namespace std;
    double temp;
    int i;
    for (i=0;i<limit;i++)
    {
        cout<<"Please enter a number: ";
        if (cin>>temp)
            arr[i]=temp;
        else
        {
            cin.clear();
            while (cin.get()!='\n')
                continue;
            cout<<"Bad input!\n";
            break;
        }
    }
    return i;
}

void show_array(const double arr[],int limit)
{
    using namespace std;
    cout<<"Numbers: ";
    for (int i=0;i<limit;i++)
        cout<<arr[i]<<" ";
    cout<<endl;
}
void reverse_array(double arr[],int limit)
{
    double swap;
    int i;
    for (i=0;limit-->i;i++)//关键!交换不会反转的核心
    {
        swap=arr[limit];//经典交换模型
        arr[limit]=arr[i];
        arr[i]=swap;
    }
}

//PP7.13.7
#include <iostream>
const int Max =5;
double* fill_array(double ar[],int limit);//填充数组函数,返回实际数组末尾指针
void show_array(const double *,const double *);
void revalue(double r,double *,double *);

int main()
{
    using namespace std;
    double properties[Max];//定义一个数组记录财产

    double* size=fill_array(properties,Max);//获取返回的数组指针
    show_array(properties,size);
    if (size>0)
    {
        cout<<"\n\nEnter revaluation factor:";
        double factor;//输入重新评估因子用于修改数组中的值
        while (!(cin>>factor))//输入失败检测模块
        {
            cin.clear();
            while (cin.get()!='\n')
                continue;
            cout<<"Bad input;please enter a number: ";
        }
        revalue(factor,properties,size);//调用修改数组函数
        show_array(properties,size);//显示修改后的数组函数
    }
    cout<<"\n\nDone.\n";
    cin.get();//光标浮动以等待输入
    return 0;
}

double* fill_array(double ar[],int limit)
{
    using namespace std;
    double temp;
    int i;
    for (i=0;i<limit;i++)
    {
        cout<<"Enter value#"<<(i+1)<<": ";
        cin>>temp;//读取并写入数组
        if (!cin)//输入失败检测模块
        {
            cin.clear();
            while (cin.get()!='\n')
                continue;
            cout<<"Bad input;input  process terminated.\n";
            break;
        }
        else if (temp<0)//输入负数跳出读取
            break;
        ar[i]=temp;//如果非负则赋值成功
    }
    double* ip=&ar[i];
    return ip;
}

void show_array(const double* a,const double* b)
{
    using namespace std;
    cout<<"\nProperty: $";
    for (a;a!=b;a++)//注意指针的条件判断方式
    {
        cout<<*a<<" ";
    }
}

void revalue(double r,double* a,double* b)
{
    for (a;a!=b;a++)
        (*a)*=r;
}

//PP7.13.8.a
#include <iostream>

const int Seasons=4;
const char* Sname[Seasons] {"Spring","Summer","Fall","Winter"};
void fill(double*);
void show(double*);
int main()
{
    double expenses[Seasons] {0};
    fill(expenses);//传递指针
    show(expenses);
    return 0;
}

void fill(double arr[])
{
    using namespace std;
    for (int i=0;i<Seasons;i++)
    {
        cout<<"Enter "<<Sname[i]<<" expenses: ";
        cin>>arr[i];//此处括号必不可少
    }
}

void show(double arr[])
{
    using namespace std;
    double total=0.0;
    cout<<"\nEXPENSES\n";
    for (int i=0;i<Seasons;i++)
    {
        cout<<Sname[i]<<": $"<<arr[i]<<endl;
        total+=arr[i];//求和
    }
    cout<<"Total Expenses: $"<<total<<endl;
}

//PP7.13.8.b R
#include <iostream>//细心再细心啊!!
const int Seasons=4;
struct expense_s
{
    double expense_arr[Seasons] {0};
};//结构定义在函数原型前,避免函数原型声明无效
const char* Sname[Seasons] {"Spring","Summer","Fall","Winter"};
expense_s fill(expense_s t);
void show(const expense_s* t1);
int main()
{
    expense_s sear;
    sear=fill(sear);//传递结构
    std::cout<<sear.expense_arr[2];
    show(&sear);//传递结构指针
    return 0;
}

expense_s fill(expense_s t1)
{
    using namespace std;
    for (int i=0;i<Seasons;i++)
    {
        cout<<"Enter "<<Sname[i]<<" expenses: ";
        cin>>t1.expense_arr[i];//结构式存储
    }
    return t1;//传递结构记得返回!!!
}

void show(const expense_s* t1)
{
    using namespace std;
    double total=0.0;
    cout<<"\nEXPENSES\n";
    for (int i=0;i<Seasons;i++)
    {
        cout<<Sname[i]<<": $"<<t1->expense_arr[i]<<endl;
        total+=t1->expense_arr[i];//求和
    }
    cout<<"Total Expenses: $"<<total<<endl;
}

//PP7.13.9
#include <iostream>
using namespace std;
const int SLEN=30;
struct student
{
    char fullname[SLEN];
    char hobby[SLEN];
    int opplevel;
};
int getinfo(student pa[],int n);
void display1(student st);
void display2(const student* ps);
void display3(const student pa[],int n);
int main()
{
    cout<<"Enter calss size: ";
    int class_size;
    cin>>class_size;
    while (cin.get()!='\n')
        continue;
    student* ptr_stu=new student[class_size];
    int entered=getinfo(ptr_stu,class_size);
    for (int i=0;i<entered;i++)
    {
        display1(ptr_stu[i]);
        display2(&ptr_stu[i]);
    }
    display3(ptr_stu,entered);
    delete [] ptr_stu;
    cout<<"Done\n";
    return 0;
}

int getinfo(student pa[],int n)
{
    using namespace std;
    int i;
    for (i=0;i<n;i++,pa++)
    {
        cout<<"Enter #"<<i+1<<" Student name: ";
        cin>>pa->fullname;
        cout<<"Enter #"<<i+1<<" Student hobby: ";
        cin>>pa->hobby;
        cout<<"Enter #"<<i+1<<" Student opplevel: ";
        cin>>pa->opplevel;
        while (!cin)
        {
            cin.clear();
            --i;//输入错误重新返回i值
            cout<<"Bad input.\n";
            while (cin.get()!='\n')
                continue;
        }
    }
    return i;
}

void display1(student st)
{
    using namespace std;
    cout<<"Student name: "<<st.fullname<<endl;
    cout<<"Student hobby: "<<st.hobby<<endl;
    cout<<"Student opplevel: "<<st.opplevel<<endl;
}

void display2(const student* ps)
{
    using namespace std;
    cout<<"Student name: "<<ps->fullname<<endl;
    cout<<"Student hobby: "<<ps->hobby<<endl;
    cout<<"Student opplevel: "<<ps->opplevel<<endl;
}

void display3(const student pa[],int n)
{
    using namespace std;
    for (int i=0;i<n;pa++,i++)
    {
        cout<<"Student name #"<<i+1<<": "<<pa->fullname<<endl;
        cout<<"Student hobby #"<<i+1<<": "<<pa->hobby<<endl;
        cout<<"Student opplevel #"<<i+1<<": "<<pa->opplevel<<endl;
    }
}

//PP7.13.10 R
#include <iostream>
const int ArSize=3;
double calculate(double n1,double n2,double (*ptr)(double, double));
double add(double,double);
double minus_n(double,double);
double change(double,double);
void show_arr(double (*pf[ArSize])(double,double),const char**,double,double);
int main()
{
    using namespace std;
    double q=calculate(2.5,10.4,add);
    cout<<"Test: q= "<<q<<endl;
    double (*pf[ArSize])(double,double){add,minus_n,change};
    const char* npa[3] {"add","minus_n","change"};//必须加const!!!
    //必须注意npa的类型为char**!!!
    //npa为指向第一个字符串的指针!!也即指向指针(字符串)的指针(字符串)
    double n1,n2;
    cout<<"Enter the pairs numbers: (q to quit.)";
    while (cin>>n1>>n2)
    {
        show_arr(pf,npa,n1,n2);
    }
    cout<<"Done.\n";
    return 0;
}

double calculate(double n1,double n2,double (*ptr)(double, double))
{
    return (*ptr)(n1,n2);//此处ptr也可写为(*ptr)
}

double add(double x,double y)
{
    return x+y;
}

double minus_n(double x,double y)
{
    return x-y;
}

double change(double x,double y)
{
    return x*y*0.8;
}

void show_arr(double (*pf[ArSize])(double,double),const char** pn,double t1,double t2)
{
    using namespace std;
    for (int i=0;i<ArSize;i++,pn++)
        cout<<*pn<<": "<<pf[i](t1,t2)<<endl;
    //pn一接触*就指向字符串,且此处pn++移动的是数组元素间隔
}

猜你喜欢

转载自blog.csdn.net/enochhugh/article/details/70144309
pp
7.1