CPP_Basic_Code_P6.1-PP6.11.9
阿新 • • 發佈:2018-11-02
##CPP_Basic_Code_P6.1-PP6.11.9
// 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
//P6.1
#include <iostream>
int main()
{
using std::cin;
using std::cout;
char ch;
int spaces=0;//外部全域性變數
int total=0;//外部全域性變數
cin.get(ch);//讀取第一個字元
while (ch!='.')//如果不是句號則繼續迴圈
{
if (ch==' ')
++spaces;//遇到空格計數
++total;//無論是否空格均計數,且字元總數包含最後的回車生成的換行符
cin.get(ch);
}
cout<<spaces<< " spaces, "<<total
<<" characters total in sentence\n";
return 0;
}
//P6.2
#include <iostream>
int main()
{
char ch;
std::cout<<"Type,and I shall repeat.\n";
std::cin.get(ch);
while (ch!='.')
{
if (ch=='\n')
std::cout<<ch;
else
std::cout<<++ch;//此處++ch被cout理解為字元輸出,若改為ch+1則會被認為int輸出
std::cin.get(ch);
}
std::cout<<"\nPlease excuse the slight confusion.\n";
return 0;
}
//P6.3
#include <iostream>
const int fave=9;
int main()
{
using namespace std;
int n;
cout<<"Enter a number in the range 1-100 to find"
<<"my favorite number: ";
do{
cin>>n;
if (n<fave)//小了就說
cout<<"Too low! Then guess again: ";
else if (n>fave)//這種寫法實際上是一個if else被包含在另一個if else中
cout<<"Too high! Then guess again: ";
else//這樣調整後的寫法實際上更清晰更好
cout<<fave<<" is right!\n";
}while (n!=fave);//沒猜對就繼續猜
return 0;
}
//P6.4
#include <iostream>
int main()
{
using namespace std;
cout<<"This program may reformat your hard disk\n"//引號具有輸出流連續性
"and destroy all your data.\n"
"Do you wish to continue? <y/n>";
char ch;
cin>>ch;
if (ch=='y'||ch=='Y')//或運算子,或真則真,滿足其一即可
cout<<"You were warned!\a\a\n";
else if (ch=='n'||ch=='N')//再次使用
cout<<"A wise choice...Bye!\n";
else
cout<<"That's wasn't a 'Y/y' or 'N/n'!Apparently you "
"can't follow\ninstructions,so "
"I'll trash your disk anyway.\a\a\a\n";
return 0;
}
//P6.5
#include <iostream>
const int ArSize=10;//控制陣列大小,即報價個數
int main()
{
using namespace std;
float naaq[ArSize];
cout<<"Enter the NAAQs (New Age Awareness Quotients) "
<<"Of\nyour neighbors. Program terminates "
<<"when you make\n"<<ArSize<<" entries "
<<"or enter a negative value.\n";
int i=0;
float temp;
cout<<"First value: ";
cin>>temp;
while (i<ArSize&&temp>=0)//第一個條件保證陣列不溢位,第二個條件確保輸入報價有效
{
naaq[i]=temp;//有效則逐個存入陣列
++i;//陣列角標自增
if (i<ArSize)//然後如果i<ArSize說明陣列還有空間,繼續請求輸入
{
cout<<"Next value: ";
cin>>temp;//再次賦值給temp後繼續迴圈直到存滿陣列
}
}
if (i==0)//意味著輸入了一個不滿足第二個條件的數,於是未進入過while迴圈
cout<<"No data--bye\n";//如果中途輸入了負數則會跳過這裡直接到下一模組請求自己報價,因為中途i!=0
else
{
cout<<"Enter your NAAQ: ";//輸入自己的報價
float you;
cin>>you;
int count=0;//設定比較計數器
for (int j=0;j<i;j++)//迴圈次數等於ArSize,也即是逐個比較
if (naaq[j]>you)//如果之前報價你自己輸入的高,則計數器+1
++count;//逐個比較直到迴圈結束
cout<<count;//開始輸出結果
cout<<" of your naghbors have greater awareness of\n"
<<"the New Age than you do.\n";
}
return 0;
}
//P6.6
#include <iostream>
const char* qualify[4]//建立指向字串的常量指標陣列
{
"10,000-meter race.\n",
"mud tug-of-war.\n",
"masters canoe jousting.\n",
"pie-throwing festival.\n"
};
int main()
{
using namespace std;
int age;
cout<<"Enter your age in years: ";
cin>>age;
int index;
if (age>17&&age<35)//18-34
index=0;
else if (age>=35&&age<50)//35-49
index=1;
else if (age>=50&age<65)//50-64,且可見else if可以連續使用
index=2;
else //包括負數,0-17,65以上;但是年齡預設不會輸入負數
index=3;
cout<<"Your qualify for the "<<qualify[index];//輸出分級頁結果
return 0;
}
//P6.7
#include <iostream>
#include <climits>
bool is_int(double);//函式宣告
int main()
{
using namespace std;
double num;
cout<<"Yo,dude!Enter an intger value: ";
cin>>num;
while (!is_int(num))//while條件函式呼叫取反
{
cout<<"Out if range __ Please try again: ";
cin>>num;
}
int val=int (num);
cout<<"You've entered the integer "<<val<<"\nBye\n";
return 0;
}
bool is_int(double x)
{
if (x<=INT_MAX&&x>=INT_MIN)
return true;//輸入範圍成功則返回true,取反為false,則while被跳過
else
return false;//超出範圍,返回false,取反為true,則while被啟用,提示重新輸入
}
//P6.8
#include <iostream>
#include <cctype>
int main()
{
using namespace std;
cout<<"Enter text for analysis and type @"
" to terminate input.\n";
char ch;
int whitespace=0;
int digits=0;
int chars=0;
int punct=0;
int others=0;
cin.get(ch);
while (ch!='@')
{
if (isalpha(ch))//字母檢查
chars++;
else if (isspace(ch))//空白符檢查
whitespace++;
else if (isdigit(ch))//數字檢查
digits++;
else if (ispunct(ch))//標點檢查
punct++;
else
others++;//剩下的歸於其它,比如漢字等特殊符號
cin.get(ch);
}
cout<<chars<<" letters, "
<<whitespace<<" whitespace, "
<<digits<<" digits, "
<<punct<<" punctuations, "
<<others<<" others.\n";
return 0;
}
//P6.9
#include <iostream>//求出兩個數最大值
int main()
{
using namespace std;
int a,b;
cout<<"Enter two integers: ";
cin>>a>>b;
cout<<"The larger of "<<a<<" and "<<b;
int c=a>b?a:b;//使用了?:條件運算子
cout<<" is "<<c<<endl;
return 0;
}
//P6.10.V1
#include <iostream>
using namespace std;
void showmenu();//無參無返回值函式宣告
void report();
void comfort();
int main()
{
showmenu();//函式呼叫顯示選單
int choice;
cin>>choice;
while (choice!=5)
{
switch (choice)
{
case 1: cout<<"\a\n";
break;//跳出迴圈
case 2: report();
break;
case 3: cout<<"The boss was in all day.\n";
break;
case 4: comfort();
break;
default: cout<<"That's not a choice.\n";
//預設分支,後面不需要加break;
}
showmenu();
cin>>choice;
}
cout<<"Bye!\n";
return 0;
}
void showmenu()//選單函式模組
{
cout<<"Please enter 1,2,3,4,or 5:\n"
"1) alarm 2) report\n"
"3) alibi 4) comfort\n"
"5) quit\n";
}
void report()//報告函式模組
{
cout<<"It's been an excellent week for business.\n"
"Sales are up 120$. Expense are down 35%.\n";
}
void comfort()//安撫模組
{
cout<<"Your employees think you are the finest CEO\n"
"in the industry .The board of directors thinks\n"
"you are the finest CEO in the industry.\n";
}
//P6.10.V2
#include <iostream>
using namespace std;
void showmenu();//無參無返回值函式宣告
void report();
void comfort();
int main()
{
showmenu();//函式呼叫顯示選單
char choice;//使用英文字元控制
cin>>choice;
while (choice!='Q'&&choice!='q')
{
switch (choice)
{
case 'a'://利用連續執行的特性解決大小寫的問題
case 'A': cout<<"\a\n";
break;//跳出迴圈
case 'b':
case 'B': report();
break;
case 'c':
case 'C': cout<<"The boss was in all day.\n";
break;
case 'd':
case 'D': comfort();
break;
default: cout<<"That's not a choice.\n";//預設分支,後面不需要加break;
}
showmenu();
cin>>choice;
}
cout<<"Bye!\n";
return 0;
}
void showmenu()//選單函式模組
{
cout<<"Please enter 1,2,3,4,or 5:\n"
"a) alarm b) report\n"
"c) alibi d) comfort\n"
"q) quit\n";
}
void report()//報告函式模組
{
cout<<"It's been an excellent week for business.\n"
"Sales are up 120$. Expense are down 35%.\n";
}
void comfort()//安撫模組
{
cout<<"Your employees think you are the finest CEO\n"
"in the industry .The board of directors thinks\n"
"you are the finest CEO in the industry.\n";
}
//P6.11
#include <iostream>
enum {red,orange,yellow,green,blue,violet,indigo};
//int型別 0,1,2,3,4,5,6
//列舉常量宣告,沒用變數名,注意逗號,結尾分號,和結構宣告類似
int main()
{
using namespace std;
cout<<"Enter color code (0-6): ";
int code;
cin>>code;
while (code>=red&&code<=indigo)//範圍限定在0-6之間
{
switch (code)//標籤
{
case red: cout<<"Her lips were red.\n";break;//注意此處有兩個分號
case orange: cout<<"Her hair was orange.\n";break;
case yellow: cout<<"Her shoes were yellow.\n";break;
case green: cout<<"Her nails were green.\n";break;
case blue: cout<<"Her sweatsuit was blue.\n";break;
case violet: cout<<"Her eyes were violet.\n";break;
case indigo: cout<<"Her mood was indigo.\n";break;
}
cout<<"Enter color code (1-6)";
cin>>code;
}
cout<<"Bye.\n";
return 0;
}
//P6.12
#include <iostream>
const int ArSize=80;
int main()
{
using namespace std;
char line[ArSize];//設定字元陣列
int spaces=0;//初始化空格計數器
cout<<"Enter a line of text:\n";
cin.getline(line,ArSize);//字元讀入line陣列中
cout<<"Complete line:\n"<<line<<endl;
cout<<"Line through first period:\n";
for (int i=0;line[i]!='\0';i++)//沒碰到陣列結尾\0將繼續迴圈,逐個輸出陣列中的字元
{
cout<<line[i];
if (line[i]=='.')//檢測到句點則離開迴圈
break;
if (line[i]!=' ')//檢測不到空格則回到for的迴圈更新處,即i++後繼續迴圈
continue;
spaces++;//有空格將會到達此處,空格計數器
}
cout<<"\n"<<spaces<<" sapces\n";
cout<<"Done.\n";
return 0;
}
//P6.13
#include <iostream>
const int Max=5;
int main()
{
using namespace std;
double fish[Max];//初始化存重量的陣列
cout<<"Please enter the weights of your fish.\n";
cout<<"You may enter up to "<<Max<<"fish <q to terminate>,\n";
cout<<"fish #1: ";
int i=0;
while (i<Max&&cin>>fish[i])//且假則假,因此當左側為false,右側不會被判斷,防止陣列溢位
{
if (++i<Max)
cout<<"fish #"<<i+1<<": ";//輸出魚的編號
}
double total =0.0;//設定重量計數器
for (int j=0;j<i;j++)
total+=fish[j];//統計整個陣列的魚總量
if (i==0)
cout<<"No fish\n";
else cout<<total/i<<" = average weight of "<<i<<" fish\n";//計算平均值
cout<<"Done.\n";
return 0;
}
//P6.14
#include <iostream>//可阻止非法輸入並給出正確的提示
const int Max=5;
int main()
{
using namespace std;
int golf[Max];
cout<<"Please enter your golf scores.\n";
cout<<"You must enter "<<Max<<" rounds.\n";
int i;
for (i=0;i<Max;i++)
{
cout<<"round #"<<i+1<<": ";
while (!(cin>>golf[i]))//輸入失敗返回false,取反為true即啟用錯誤處理
{
cin.clear();//重置cin