c++ primer plus 习题答案(1)
c++ primer plus 习题答案用的是第五版,IDE仍然是vs2013。我只标注了题号,具体的题目找下书上对应内容吧。
p110.8
1 #include<iostream> 2 #include<string> 3 #include<cstring> 4 char* getname(char*); 5 6 struct pissza { 7 char *pt; 8 int diameter; 9 int weight; 10 }; 11 12 using namespace std; 13 int main(void){ 14 pissza will; 15 getname(will.pt); 16 cout << "enter a diameter\n"; 17 cin >> will.diameter; 18 cout << "enter a weight\n"; 19 cin >> will.weight; 20 cout << will.pt << " has a pissza " << will.diameter 21 << " m " << will.weight << " g\n"; 22 cin.get(); 23 cin.get(); 24 return 0; 25 } 26 27 char* getname(char*pt){ 28 char name[20]; 29 cout << "enter a name\n"; 30 cin.getline(name, 20); 31 pt = new char[strlen(name) + 1]; 32 strcpy(pt, name); 33 return pt; 34 }
p180.2
1 #include<iostream> 2 #include<ctime> 3 #include<cstdlib> 4 5 int main(void){ 6 using namespace std; 7 int i, j, count=0, sum = 0, pt[10]; 8 double mean; 9 for (i = 0; i < 10; i++){ 10 if (!(cin >> pt[i])) 11 break; 12 sum += pt[i]; 13 } 14 mean = sum / i; 15 for (j = 0; j <= i; j++) 16 if (pt[j]>mean) 17 count++; 18 cout << "mean is " << mean << endl; 19 cout << "there " << count << " exceed mean\n"; 20 21 int time=10; 22 clock_t delay = time* CLOCKS_PER_SEC; 23 clock_t start = clock(); 24 while (clock() - start < delay) 25 continue; 26 27 return 0; 28 }
p181.7
1 #include<iostream> 2 #include<cstdlib> 3 #include<cctype> 4 #include<string> 5 using namespace std; 6 7 int main(){ 8 string word; 9 int vowel = 0, con = 0, other=0; 10 while (cin >> word && word != "q"){ 11 if (isalpha(word[0])) 12 switch (word[0]){ 13 case ‘A‘: 14 case ‘a‘: 15 vowel++; 16 continue; 17 case ‘E‘: 18 case ‘e‘: 19 vowel++; 20 continue; 21 case ‘I‘: 22 case ‘i‘: 23 vowel++; 24 continue; 25 case ‘O‘: 26 case ‘o‘: 27 vowel++; 28 continue; 29 case ‘U‘: 30 case ‘u‘: 31 vowel++; 32 continue; 33 default: con++; 34 } 35 else other++; 36 } 37 38 cout << vowel << "words beginning with vowels\n"; 39 cout << con << "words beginning with consonants\n"; 40 cout << other << "others\n"; 41 42 system("pause"); 43 return 0; 44 }
p181.8
1 #include<iostream> 2 #include<cstdlib> 3 #include<cctype> 4 #include<string> 5 #include<fstream> 6 using namespace std; 7 8 int main(){ 9 string name; 10 cout << "enter the file name\n"; 11 getline(cin, name); 12 ifstream inFile; 13 inFile.open(name); 14 if (!inFile.is_open()){ 15 cout << "can‘t open the file\n"; 16 exit(EXIT_FAILURE); 17 } 18 char ch; 19 int count = 0; 20 inFile >> ch; 21 while (inFile.good()){ 22 count++; 23 inFile >> ch; 24 } 25 if (inFile.eof()) 26 cout << "reading completed successfully\n"; 27 else if (inFile.fail()) 28 cout << "reading terminated by data dismatch\n"; 29 if (count == 0) 30 cout << "no data processed\n"; 31 else 32 cout << "count is " << count << endl; 33 inFile.close(); 34 system("pause"); 35 return 0; 36 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。