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();//聲明沒(méi)有返回值的函數(shù)
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()//具體的函數(shù)編寫
{
using namespace std;
cout<<"I'm but s simple function.\n";
}
//P7.2
#include <iostream>
void cheers(int);
double cube(double x);//有返回值的函數(shù)
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);//注意調(diào)用方式
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)//子函數(shù)全部使用內(nèi)部的局部變量
{
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;//利用連乘實(shí)現(xiàn)計(jì)算且避免中間數(shù)過(guò)大
return result;//返回結(jié)果
}
//P7.5
#include <iostream>
const int ArSize=8;
int sum_arr(int arr[],int n);//聲明傳遞數(shù)組的函數(shù)料仗,指針和整數(shù)
//此處也可使用int* arr來(lái)實(shí)現(xiàn)數(shù)組的聲明
int main()
{
using namespace std;
int cookies[ArSize] {1,2,4,8,16,32,64,128};
int sum=sum_arr(cookies,ArSize);//函數(shù)調(diào)用后賦值
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];//傳遞的指針可當(dāng)做數(shù)組名使用
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, ";//數(shù)組名輸出將輸出數(shù)組地址
std::cout<<sizeof cookies<<" = sizeof cookies\n";//輸出數(shù)組名大小將輸出整個(gè)數(shù)組大小
int sum=sum_arr(cookies,ArSize);//函數(shù)調(diào)用后賦值
std::cout<<"Total cookies eaten: "<<sum<<std::endl;
sum=sum_arr(cookies,3);//傳遞參數(shù)指出數(shù)組只有三個(gè)元素從而計(jì)算前三者總和
std::cout<<"First three eaters ate "<<sum<<" cookies.\n";
sum=sum_arr(cookies+4,4);//使用指針加減來(lái)移動(dòng)指針位置到第五個(gè)元素,往后四個(gè)
//此處也可以使用&cookies[4]來(lái)取代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, ";//輸出指針(數(shù)組名)地址
std::cout<<sizeof arr<<" = sizeof arr\n";//輸出指針長(zhǎng)度
for (int i=0;i<n;i++)
total=total+arr[i];//傳遞的指針可當(dāng)做數(shù)組名使用
return total;
}
//P7.7
#include <iostream>
const int Max =5;
int fill_array(double ar[],int limit);//填充數(shù)組函數(shù)字逗,返回輸入的個(gè)數(shù)
void show_array(const double ar[],int n);//打印函數(shù)京郑,無(wú)返回值
void revalue(double r,double ar[],int n);//修改數(shù)組函數(shù),直接修改數(shù)組無(wú)返回值
int main()
{
using namespace std;
double properties[Max];//定義一個(gè)數(shù)組記錄財(cái)產(chǎn)
int size=fill_array(properties,Max);//將實(shí)際輸出的元素?cái)?shù)賦值到size
show_array(properties,size);//打印size個(gè)財(cái)產(chǎn)
if (size>0)
{
cout<<"Enter revaluation factor: ";
double factor;//輸入重新評(píng)估因子用于修改數(shù)組中的值
while (!(cin>>factor))//輸入失敗檢測(cè)模塊
{
cin.clear();
while (cin.get()!='\n')
continue;
cout<<"Bad input;please enter a number: ";
}
revalue(factor,properties,size);//調(diào)用修改數(shù)組函數(shù)
show_array(properties,size);//顯示修改后的數(shù)組函數(shù)
}
cout<<"Done.\n";
cin.get();//光標(biāo)浮動(dòng)以等待輸入
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;//讀取并寫入數(shù)組
if (!cin)//輸入失敗檢測(cè)模塊
{
cin.clear();
while (cin.get()!='\n')
continue;
cout<<"Bad input;input process terminated.\n";
break;
}
else if (temp<0)//輸入負(fù)數(shù)跳出讀取
break;
ar[i]=temp;//如果非負(fù)則賦值成功
}
return i;
}
void show_array(const double ar[],int n)
{
using namespace std;
for (int i=0;i<n;i++)
{
cout<<"Property #"<<(i+1)<<": $";//循環(huán)打印數(shù)組
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);//定義數(shù)組區(qū)別函數(shù)葫掉,用指針區(qū)間傳遞參數(shù)
int main()
{
using namespace std;
int cookies[ArSize] {1,2,4,8,16,32,64,128};
int sum=sum_arr(cookies,cookies+ArSize);//區(qū)間為1~ArSize
cout<<"Total cookies eaten: "<<sum<<endl;
sum=sum_arr(cookies,cookies+3);//傳遞參數(shù)指出數(shù)組只有三個(gè)元素從而計(jì)算前三者總和
cout<<"First three eaters ate "<<sum<<" cookies.\n";
sum=sum_arr(cookies+4,cookies+8);//使用指針區(qū)間指定后四個(gè)元素
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為最后一個(gè)元素的后面一個(gè)位置
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');//指針參數(shù)和特征字符參數(shù)
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表示的第一個(gè)字符些举,不為空值符就繼續(xù)循環(huán)直到'\0'
{
if (*str==ch)
count++;
str++;//移動(dòng)指針繼續(xù)指向下一個(gè)字符
}
return count;
}
//P7.10
#include <iostream>
char* buildstr(char c,int n);//返回指針的函數(shù)聲明
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;//釋放子函數(shù)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];//創(chuàng)建指針指向次數(shù)+1,因?yàn)榻Y(jié)尾是'\0'
pstr[n]='\0';//設(shè)置結(jié)尾
while (n-->0)//n減到0
pstr[n]=c;//將字符c的值賦值給數(shù)組中各元素位置
return pstr;//返回字符串指針俭厚,new出來(lái)的地址
}
//P7.11
#include <iostream>
struct travel_time
{
int hours;
int mins;
};
const int Mins_per_hr=60;//1小時(shí)=60分
travel_time sum(travel_time t1,travel_time t2);//返回結(jié)構(gòu)的函數(shù)原型聲明户魏,接收2個(gè)結(jié)構(gòu)參數(shù)
void show_time(travel_time t);//顯示結(jié)構(gòu),接收1個(gè)結(jié)構(gòu)參數(shù)
int main()
{
using namespace std;
travel_time day1={5,45};//注意結(jié)構(gòu)不用()用{}
travel_time day2={4,55};
travel_time trip=sum(day1,day2);//結(jié)構(gòu)賦值
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;//取模獲得剩余分鐘數(shù)
total.hours=t1.hours+t2.hours+(t1.mins+t2.mins)/Mins_per_hr;//除法獲得小時(shí)數(shù)
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//極坐標(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)
int main()
{
using namespace std;
rect rplace;//聲明兩個(gè)結(jié)構(gòu)以存儲(chǔ)輸入的數(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;
}
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";
}
//P7.13
#include <iostream>
#include <cmath>
struct polar//極坐標(biāo)結(jié)構(gòu)
{
double distance;
double angle;
};
struct rect//直角坐標(biāo)結(jié)構(gòu)
{
double x;
double y;
};
void rect_to_polar(const rect* pxy,polar* pda);//傳遞指針叼丑,第二個(gè)需要修改故不const
void show_polar(const polar* pda);//顯示極坐標(biāo)
int main()
{
using namespace std;
rect rplace;//聲明兩個(gè)結(jié)構(gòu)以存儲(chǔ)輸入的數(shù)據(jù)
polar pplace;
cout<<"Enter the x and y value: ";
while (cin>>rplace.x>>rplace.y)//連續(xù)使用cin可行,且忽略空格等
{
rect_to_polar(&rplace,&pplace);//結(jié)果賦值給第二個(gè)結(jié)構(gòu)
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);//指針使用->來(lái)控制成員
pda->angle=atan2(pxy->y,pxy->x);
}
void show_polar(const polar* pda)
{
using namespace std;
const double Rad_to_deg=57.29577951;//弧度轉(zhuǎn)換為度數(shù)的常數(shù)因子
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);//調(diào)用顯示模塊
return 0;
}
void display(const string sa[],int n)//傳遞數(shù)組指針和容量參數(shù)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);//傳遞地址指針效率高但是看起來(lái)復(fù)雜
show(expenses);//傳遞實(shí)體效率低下
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];//此處括號(hào)必不可少
}
}
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;//逆向退出程序隊(duì)列故反向輸出
}
//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';//結(jié)尾處填充結(jié)束的\0
int max=Len-2;//數(shù)組\0前的最后一個(gè)元素
int min=0;//數(shù)組第一個(gè)元素
ruler[min]=ruler[max]='|';//首尾填充|
std::cout<<ruler<<std::endl;
for (i=1;i<=Divs;i++)//一下循環(huán)ivs次
{
subdivide(ruler,min,max,i);
std::cout<<ruler<<std::endl;
for (int j=1;j<Len-2;j++)
ruler[j]=' ';//每次均重新填充空格再繼續(xù)下一次循環(huán)
}
return 0;
}
void subdivide(char ar[],int low,int high,int level)
{
if (0==level)
return;//返回到主函數(shù)處繼續(xù)執(zhí)行
int mid=(high+low)/2;//求出中間元素的位置數(shù)
ar[mid]='|';//將中間這個(gè)位置填充|
subdivide(ar,low,mid,level-1);//繼續(xù)調(diào)用遞歸扛门,但是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));//聲明了函數(shù)指針
//(*pf)等同函數(shù)名效果鸠信,兩者用法一致;且因歷史原因论寨,pf等價(jià)于(*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);//調(diào)用函數(shù)指針betsy星立,函數(shù)名即地址爽茴,可傳遞
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";//函數(shù)指針調(diào)用來(lái)計(jì)算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種函數(shù)聲明是完全相同的效果
int main()
{
using namespace std;
double av[3] {1112.3,1542.6,2227.9};
const double *(*p1) (const double *,int)=f1;//定義函數(shù)指針p1,初始化指向f1
auto p2=f2;//自動(dòng)推導(dǎo)來(lái)自定義初始化p2绰垂,指向f2
cout<<"Using pointers to functions:\n";
cout<<"Address Value\n";
cout<<(*p1)(av,3)<<": "<<*(*p1)(av,3)<<endl;
//第一個(gè)函數(shù)調(diào)用返回double*地址闹啦,第二個(gè)解除引用將返回指向的具體double值
cout<<p2(av,3)<<": "<<*p2(av,3)<<endl;
//p2和(*p2)在函數(shù)調(diào)用時(shí)是完全等價(jià)的(C++規(guī)定),解除只需同樣左加*即可
const double *(*pa[3])(const double *,int) {f1,f2,f3};
//pa是一個(gè)數(shù)組辕坝,它的元素是指針窍奋,且這些指針是函數(shù)指針,分別指向f1,f2,f3
//這些函數(shù)指針的返回類型是double*
auto pb=pa;//聲明同樣類型的數(shù)組
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;//指向整個(gè)數(shù)組的指針酱畅,也就是指向數(shù)組指針的指針
cout<<(*pc)[0](av,3)<<": "<<*(*pc)[0](av,3)<<endl;
const double *(*(*pd)[3])(const double *,int)=&pa;
//pd是一個(gè)指針琳袄,且是一個(gè)指向數(shù)組的指針
//而數(shù)組的元素也是指針,且是函數(shù)指針纺酸,返回double*
const double * pdb=(*pd)[1](av,3);//pd是pa的地址窖逗,故(*pd)就是數(shù)組名
cout<<pdb<<": "<<*pdb<<endl;//前者是函數(shù)返回的地址,后者是函數(shù)的實(shí)際返回值
cout<<(*(*pd)[2])(av,3)<<": "<<*(*(*pd)[2])(av,3)<<endl;
//數(shù)組元素(*pd)[2]是一個(gè)函數(shù)指針餐蔬,解除引用后是函數(shù)調(diào)用碎紊,返回地址
//后者再次解除引用就獲得函數(shù)實(shí)際返回值
return 0;
}
const double* f1(const double ar[],int n)
{
return ar;
}
const double* f2(const double ar[],int n)
{
return ar+1;//指針右移到下1個(gè)數(shù)組元素
}
const double* f3(const double ar[],int n)
{
return ar+2;//指針右移到下2個(gè)數(shù)組元素
}
//PP7.13.1
#include <iostream>
void show();
double thpjs(double x,double y);
double n1,n2;
int main()
{
using namespace std;
show();//調(diào)用函數(shù)不加前面的返回值類型
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)//計(jì)算函數(shù)
{
return 2.0*x*y/(x+y);
}
void show()//讀取數(shù)據(jù)
{
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);//務(wù)必注意const必須全部到位!
const int ArSize=10;
int main()
{
using namespace std;
double score_list[ArSize] {0};//初始化成績(jī)數(shù)組
int realsize=score_input(score_list,ArSize);//獲取數(shù)據(jù)同時(shí)返回實(shí)際輸入的值
double averagex=score_average(score_list,realsize);//調(diào)用函數(shù)獲取數(shù)組平均值
score_show(score_list,realsize,averagex);//顯示函數(shù)
return 0;
}
int score_input(double arr[],int limit)
{
using namespace std;
double temp=0;//輸入安全檢測(cè)臨時(shí)變量
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)//輸入無(wú)效跳出
break;
arr[i]=temp;//有效則賦值
}
return i;//返回實(shí)際輸入的個(gè)數(shù)
}
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);//按實(shí)值傳遞讀取輸入
box show_real_value(box rv);//按實(shí)值傳遞顯示
void input_pointer(box* spr);//按指針傳遞讀取輸入
void show_pointer(const box* spr);//按指針傳遞顯示
int main()
{
using namespace std;
box xv1;
xv1=input_real_value(xv1);//讀取數(shù)據(jù)到xv1
show_real_value(xv1);//顯示讀入的數(shù)據(jù)
box* xv2=new box;//指針指向new出的box結(jié)構(gòu)
input_pointer(xv2);//讀取輸入到指針指向的結(jié)構(gòu)
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;//數(shù)據(jù)可以連續(xù)讀取
rv.volume=rv.height*rv.width*rv.length;//體積計(jì)算
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;//指針式連續(xù)讀取
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)
//同時(shí)讀取三個(gè)參數(shù)
{
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;//利用連乘實(shí)現(xiàn)計(jì)算且避免中間數(shù)過(guò)大
result=result*(1/extr);
return result;//返回結(jié)果
}
//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);//遞歸關(guān)鍵核心
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);//指針右移一個(gè)元素以及長(zhǎng)度縮短兩個(gè)元素
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++)//關(guān)鍵!交換不會(huì)反轉(zhuǎn)的核心
{
swap=arr[limit];//經(jīng)典交換模型
arr[limit]=arr[i];
arr[i]=swap;
}
}
//PP7.13.7
#include <iostream>
const int Max =5;
double* fill_array(double ar[],int limit);//填充數(shù)組函數(shù)词爬,返回實(shí)際數(shù)組末尾指針
void show_array(const double *,const double *);
void revalue(double r,double *,double *);
int main()
{
using namespace std;
double properties[Max];//定義一個(gè)數(shù)組記錄財(cái)產(chǎn)
double* size=fill_array(properties,Max);//獲取返回的數(shù)組指針
show_array(properties,size);
if (size>0)
{
cout<<"\n\nEnter revaluation factor:";
double factor;//輸入重新評(píng)估因子用于修改數(shù)組中的值
while (!(cin>>factor))//輸入失敗檢測(cè)模塊
{
cin.clear();
while (cin.get()!='\n')
continue;
cout<<"Bad input;please enter a number: ";
}
revalue(factor,properties,size);//調(diào)用修改數(shù)組函數(shù)
show_array(properties,size);//顯示修改后的數(shù)組函數(shù)
}
cout<<"\n\nDone.\n";
cin.get();//光標(biāo)浮動(dòng)以等待輸入
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;//讀取并寫入數(shù)組
if (!cin)//輸入失敗檢測(cè)模塊
{
cin.clear();
while (cin.get()!='\n')
continue;
cout<<"Bad input;input process terminated.\n";
break;
}
else if (temp<0)//輸入負(fù)數(shù)跳出讀取
break;
ar[i]=temp;//如果非負(fù)則賦值成功
}
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];//此處括號(hào)必不可少
}
}
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>//細(xì)心再細(xì)心巴菏取!顿膨!
const int Seasons=4;
struct expense_s
{
double expense_arr[Seasons] {0};
};//結(jié)構(gòu)定義在函數(shù)原型前锅锨,避免函數(shù)原型聲明無(wú)效
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);//傳遞結(jié)構(gòu)
std::cout<<sear.expense_arr[2];
show(&sear);//傳遞結(jié)構(gòu)指針
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];//結(jié)構(gòu)式存儲(chǔ)
}
return t1;//傳遞結(jié)構(gòu)記得返回!A滴帧必搞!
}
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;//輸入錯(cuò)誤重新返回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!D矣健恕洲!
//必須注意npa的類型為char**!!!
//npa為指向第一個(gè)字符串的指針!匆笤!也即指向指針(字符串)的指針(字符串)
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++移動(dòng)的是數(shù)組元素間隔
}