1. 程式人生 > >C++ Primer Plus第六版編程練習---第6章 分支語句和邏輯運算符

C++ Primer Plus第六版編程練習---第6章 分支語句和邏輯運算符

character value ati ostream wing style ces col code

1、

 1 #include <iostream>
 2 #include <string>
 3 #include <cctype>
 4 
 5 int main()
 6 {
 7     std::string inputStr;
 8     std::cout<<"Enter your character list. enter @ to end." << std::endl;
 9     char ch;
10     std::string srcStr;
11     std::string dstStr;
12     while
(std::cin.get(ch)) 13 { 14 if(ch == @) 15 { 16 std::cout << "input befor exchane: " << srcStr << std::endl; 17 std::cout << "input after exchane: " << dstStr << std::endl; 18 break; 19 } 20 srcStr = srcStr + ch;
21 if(islower(ch)) 22 { 23 dstStr = dstStr + char(toupper(ch)); 24 continue; //必須有continue,否則全轉為小寫了 25 } 26 if(isupper(ch)) 27 { 28 dstStr = dstStr + char(tolower(ch)); 29 continue; 30 } 31 dstStr = dstStr + ch; //
其他字符原樣顯示 32 } 33 return 0; 34 }

2、

 1 #include <iostream>
 2 #include <array>
 3 
 4 int main()
 5 {
 6     const int size = 10;
 7     std::array<double,size> donation;
 8     double sum = 0.0;
 9     double avrgValue = 0.0;
10     int countLager = 0;
11     int enterNum = 0;
12     std::cout<<"Pleas enter up 10 double value, Non-digital to exit."<<std::endl;
13     while((enterNum < size) && (std::cin>>donation[enterNum]))
14     {
15         sum += donation[enterNum];
16         enterNum++;
17     }
18     avrgValue = sum/enterNum;
19     for(int i=0; i<enterNum;i++)
20     {
21         if(donation[i] > avrgValue)
22         {
23             countLager++;
24         }
25     }
26 
27     std::cout<<"There have " << countLager << " larger than everage." << std::endl;
28 
29     return 0;
30 }

3、

 1 #include <iostream>
 2 #include <string>
 3 
 4 void useage()
 5 {
 6     std::cout<<"Please enter one of the following choices:"<<std::endl;
 7     std::cout<<"c) carnivore\t"<<"p) pianist"<<std::endl;
 8     std::cout<<"t) tree\t\t"<<"g) game"<<std::endl;
 9 }
10 
11 void tip()
12 {
13     std::cout<<"Please enter a c, p, t or g: ";
14 }
15 int main()
16 {
17     useage();
18     char ch;
19     while(true)
20     {
21         std::cin>>ch;
22         if(ch != c && ch != p && ch != t && ch != g)
23         {
24             tip();
25             continue;
26         }
27         if(ch == c)
28         {
29             std::cout<<"A tager is a carnivore." << std::endl;
30             continue;
31         }
32         if(ch == p)
33         {
34             std::cout<<"Beethoven is a pianist." << std::endl;
35             continue;
36         }
37         if(ch == t)
38         {
39             std::cout<<"A maple is a tree." << std::endl;
40             continue;
41         }
42         if(ch == g)
43         {
44             std::cout<<"Chess is a game." << std::endl;
45             continue;
46         }
47     }
48     return 0;
49 }

C++ Primer Plus第六版編程練習---第6章 分支語句和邏輯運算符