C++Primer Plus笔记——第五章 循环及关系表达式及课后编程练习答案
发布日期:2021-06-29 01:50:48 浏览次数:2 分类:技术文章

本文共 12414 字,大约阅读时间需要 41 分钟。

本章小结

        循环结构可以让程序处理各类重复操作。for语句是最常用且功能最强的循环语句,如果恰当地使用for语句,可以对控制变量、判断条件、递增/递减操作和循环体等各种要素进行全面的管理。在一些情况下使用 while或do… while语句来代替for语句可以得到更加优化的循环结构。在实际进行程序设计时,有许多问题需要使用选择结构或循环结构的嵌套来解决,这往往会增加程序的复杂程度    

c++提供了3种循环:for循环、while循环和do while循环,如果循环测试条件为true 或非零,则循环将重复执行一组指令:如果测试条件为false或0,则结束箱环。for循环和while循环都是入口条件循环,这意味着程序将在执行循环体中的语句之前检查测试条件。do while循环是出口条件循环,这意味着其将在执行循环体中的语句之后检查条件。   
每种循环的句法都要求循环体由一条语句组成。然而,这条语句可以是复合语句,也可以是语句块( 由花括号括起的多条语句)。   
关系表达式对两个值进行比较,常被用作循环测试条件。关系表达式是通过使用6种关系运算符之构成的:<、<=、==、>=、>或!=。关系表达式的结果为bool类型,值为true或false。
许多程序都逐字节地读取文木输入或文本文件,istream类提供了多种可完成这种工作的方法。如果ch是一个char变量,则下面的语句将输入中的下一个字符读入到ch中:
cin>>ch;   
然而,它将忽略空格、换行符和制表符。下面的成员函数调用读取输入中的下一个字符(而不管该字符是什么)并将其存储到ch中:   
cin.get(ch);    
成员函数调用cin.get()返回下一个输入字符—包括空格、换行符和制表符,因此,可以这样使用它:    
ch = cin.get(); 
cin.get(char)成员函数调用通过返回转换为false的bool值来指出己到达EOF,而cin_get()成员函数调用则通过返回EOF值来指出已到达EOF,EOF是在iostream中定义的。

嵌套循环是循环中的循环,适用于处理二维数组。

程序清单

5.1 了解for的工作

//forloop.cpp--introducing the for loop#include "stdafx.h"#include 
int main(){ using namespace std; int i;//create a counter for (i = 0; i < 5; i++) cout << "C++ knows loops.\n"; cout << "C++ knows when to stop.\n"; return 0;}

5.2 了解for的判断特性

//num_test.cpp -- use numeric test in for loop#include "stdafx.h"#include 
int main(){ using namespace std; cout << "Enter the starting countdown value: "; int limit; cin >> limit; int i; for (i = limit; i; i--) //i = 0时结束 cout << "i = " << i << "\n"; cout << "Done now that i = " << i << "\n"; return 0;}

5.3 关系表达式

//express.cpp -- values of exprssions#include "stdafx.h"#include 
int main(){ using namespace std; int x; cout << "the express x = 100 has the value "; cout << (x = 100) << endl; cout << "Now x = " << x << endl; cout << "The expression x < 3 has the value "; cout << (x < 3) << endl; cout << "The expression x > 3 has the value "; cout << (x > 3) << endl; cout.setf(ios_base::boolalpha);//a newer C++ feature cout << "The expression x < 3 has the value "; cout << (x < 3) << endl; cout << "The expression x > 3 has the value "; cout << (x > 3) << endl; return 0;}

5.4 阶乘

//formore.cpp -- more looping with for#include "stdafx.h"#include 
int main(){ using namespace std; const int ArSize = 16; long long factorials[ArSize]; factorials[1] = factorials[0] = 1LL; for (int i = 2; i < ArSize; i++) factorials[i] = i * factorials[i - 1]; for (int i = 0; i < ArSize; i++) cout << i << "! = " << factorials[i] << endl; return 0;}

5.5 选择步长

// bigstep.cpp -- count as directed#include "stdafx.h"#include 
int main(){ using namespace std; cout << "Enter an integer: "; int by; cin >> by; cout << "Counting by " << by << "s:\n"; for (int i = 0; i < 100; i = i + by) cout << i << endl; return 0;}

5.6 大于等于

//forstr1.cpp -- using for with a string#include "stdafx.h"#include
#include
int main(){ using namespace std; cout << "Enter a word: "; string word; cin >> word; //display letters in reverse order for (int i = word.size() - 1; i >= 0; i--) cout << word[i]; cout << "\nBye.\n"; return 0;}

5.7 递增运算符

//plus_one.cpp -- the increment operator#include "stdafx.h"#include
int main(){ using namespace std; int a = 20; int b = 20; cout << "a = " << a << ": b = " << b << endl; cout << "a++ = " << a++ << ": ++b = " << ++b << endl; cout << "a = " << a << ": b = " << b << endl; return 0;}

5.8 代码块

// block.cpp -- use a block statement#include "stdafx.h"#include
int main(){ using namespace std; cout << "The Amazing Accounto will sum and averge "; cout << "five numbers for you.\n"; cout << "Please enter five values:\n"; double number; double sum = 0.0; for (int i = 1; i <= 5; i++) { cout << "Value " << i << ": "; cin >> number; sum += number; } cout << "Five exquisite choices indeed! "; cout << "They sum to " << sum << endl; cout << "and average to " << sum / 5 << ".\n"; return 0;}

5.9 两次运算

//forstr2.cpp -- reversing an array#include "stdafx.h"#include
#include
int main(){ using namespace std; cout << "Enter a word: "; string word; cin >> word; //physically modify string object char temp; int i, j; for (j = 0, i = word.size() - 1; j < i; --i, ++j) { temp = word[i]; word[i] = word[j]; word[j] = temp; } cout << word << "\nDone!\n"; return 0;}

5.10 错误

//equal.cpp -- equality vs asignment#include "stdafx.h"#include
int main(){ using namespace std; int quizscores[10] = { 20,20,20,20,20,19,20,18,20,20 }; cout << "Doing it right:\n"; int i; for (i = 0; quizscores[i] == 20; i++) cout << "quiz " << i << " is a 20\n"; cout << "Doing it dangerously wrong:\n"; for (i = 0; quizscores[i] = 20; i++)//不能使用等号赋值相当于循环一直是true,导致一直循环下去 cout << "quiz " << i << " is a 20\n"; return 0;}

5.11 strcmp()

//compstr1.cpp -- comparing string using arrays#include "stdafx.h"#include
#include
int main(){ using namespace std; char word[5] = "?ate"; for (char ch = 'a'; strcmp(word, "mate"); ch++) { cout << word << endl; word[0] = ch; } cout << "After loop ends,word is " << word << endl; return 0;}

5.12 使用string

//compstr2.cpp -- comparing strings using arrays#include "stdafx.h"#include
#include
int main(){ using namespace std; string word = "?ate"; for (char ch = 'a'; word != "mate"; ch++) { cout << word << endl; word[0] = ch; } cout << "After loop ends,word is " << word << endl; return 0;}

5.13 使用while

//while.cpp -- inroducing the while loop#include "stdafx.h"#include
const int ArSize = 20;int main(){ using namespace std; char name[ArSize]; cout << "Your first name,please: "; cin >> name; cout << "Here is your name, verticalized and ASCIIized:\n"; int i = 0; while (name[i] != '\0') { cout << name[i] << ": " << int(name[i]) << endl; i++; } return 0;}

5.14 使用clock

//waiting.cpp -- using clock() in a time-delay loop#include "stdafx.h"#include
#include
int main(){ using namespace std; cout << "Enter the delay time, in second: "; float secs; cin >> secs; clock_t delay = secs * CLOCKS_PER_SEC; cout << "starting\a\n"; clock_t start = clock(); while (clock() - start < delay); cout << "done \a\n"; return 0;}

5.15 使用do while

//dowhile.cpp -- exit-condition loop#include "stdafx.h"#include
int main(){ using namespace std; int n; cout << "Enter number in the range 1-10 to find "; cout << "my favorite number\n"; do { cin >> n; } while (n != 7); cout << "Yes, 7 is my favorite.\n"; return 0;}

5.16 总字符数

// textin1.cpp -- reading chars with a while loop#include "stdafx.h"#include
int main(){ using namespace std; char ch; int count = 0; cout << "Enter characters; enter # to quit\n"; cin >> ch; while (ch != '#') { cout << ch; ++count; cin >> ch; } cout << endl << count << " characters read\n"; return 0;}

5.17 

// textin2.cpp -- using cin.get(char)#include "stdafx.h"#include
int main(){ using namespace std; char ch; int count = 0; cout << "Enter characters; enter # to quit\n"; cin.get(ch); while (ch != '#') { cout << ch; ++count; cin.get(ch); } cout << endl << count << " characters read\n"; return 0;}

5.18 copy

// textin3.cpp -- reading chars to end of file#include "stdafx.h"#include
int main(){ using namespace std; char ch; int count = 0; cin.get(ch); while (cin.fail() == false) { cout << ch; ++count; cin.get(ch); } cout << endl << count << " characters read\n"; return 0;}

5.19 更简洁

// textin4.cpp -- reading chars with cin.get()#include "stdafx.h"#include
int main(){ using namespace std; char ch; int count = 0; while ((ch = cin.get()) != EOF) { cout.put(char(ch)); ++count; } cout << endl << count << " characters read\n"; return 0;}

5.20 二维数组

//nested.cpp -- nested loops and 2-D array#include "stdafx.h"#include 
const int Cities = 5;const int Years = 4;int main(){ using namespace std; const char * cities[Cities] = { "Gribble City", "Gribble town", "New Gribble", "San Gribble", "Gribble Vista" }; int maxtemps[Years][Cities] = { {96,100,87,101,105}, {96,98,91,107,104}, {97,101,93,108,107}, {98,103,95,109,108} }; cout << "Maximum temperatures for 2008 - 2011\n\n"; for (int city = 0; city < Cities; ++city) { cout << cities[city] << ":\t"; for (int year = 0; year < Years; ++year) cout << maxtemps[year][city] << "\t"; cout << endl; } return 0;}

课后编程习题答案

//question.cpp

#include "stdafx.h"
#include <iostream>
#include<array>
#include <string>
#include <cstring>
using namespace std;
//question 1
/*int main()
{
cout << "Please enter two integers: ";
int num1, num2;
cin >> num1 >> num2;
int sum = 0;
for (int temp = num1; temp <= num2; ++temp)
sum += temp;
cout << "The sum from " << num1 << " to " << num2 << " is " << sum << endl;
return 0;
}*/
//question 2
/*int main()
{
using namespace std;
array<long double, 101>ad = { 0 };
ad[1] = ad[0] = 1L;
for (int i = 2; i < 101; i++)
ad[i] = i * ad[i - 1];
for (int i = 0; i < 101; i++)
cout << i << "! = " << ad[i] << endl;
return 0;
}*/
//question 3
/*int main()
{
cout << "Please enter an integer: ";
int sum = 0, num;
while ((cin >> num) && num != 0)
{
sum += num;
cout << "So far, the sum is " << sum << endl;
cout << "Please enter an integer: ";
}
return 0;
}*/
//question 4
/*int main()
{
using namespace std;
double sum1, sum2;
sum1 = sum2 = 0.0;
int year = 0;
while (sum2 <= sum1)
{
++year;
sum1 += 10;
sum2 = (100 + sum2)*0.05 + sum2;
}
cout << "After " << year << " years" << endl;
cout << "Now,Cleo's value is " << sum1 
<< ",Daphne's value is "  << sum2 << endl;
return 0;
}*/
//question 5
/*int main()
{
const int MONTHS = 12;
const char* months[MONTHS]= 
{ "January  ",
 "February ",
 "March    ",
 "April    ",
 "May      ",
 "June     ",
 "July     ",
 "August   ",
 "September",
 "October  ",
 "November ",
 "December " 
};
int sales[MONTHS], sum = 0;
for (int i = 0; i < MONTHS; i++)
{
cout << "please enter the sales in " << months[i] << " : " ;
cin >> sales[i];
sum += sales[i];
}
cout << "the all sales of this years is: " << sum << endl;
return 0;
}*/
//question 6
/*int main()
{
const int MONTHS = 12;
const char* months[MONTHS] =
{   "January  ",
"February ",
"March    ",
"April    ",
"May      ",
"June     ",
"July     ",
"August   ",
"September",
"October  ",
"November ",
"December "
};
const char* years[3] = { "first","second","third" };
int year_sale[3], sum = 0, sales[3][MONTHS];
for (int i = 0; i < 3; i++)
{
int temp = 0;
cout  << "the sales of every month in " << years[i] << " year is  " << endl;
for (int j = 0; j < MONTHS; j++)
{
cout << "please enter the sale of " << months[j] << " : ";
cin >> sales[i][j];
temp += sales[i][j];
}
year_sale[i] = temp;
sum += year_sale[i];
}
for (int i = 0; i < 3; i++)
cout << "the sales of " << years[i] << " year are: " << year_sale[i] << endl;
cout << "the all sales of three years are : " << sum << endl;
return 0;
}*/
//question 6.1
/*int main()
{
const int Months = 12, Years = 3;
const char* months[Months] =
{   "January  ",
"February ",
"March    ",
"April    ",
"May      ",
"June     ",
"July     ",
"August   ",
"September",
"October  ",
"November ",
"December "
};
int sale[Years][Months] = { 0 };
for (int i = 0; i < Years; i++)
{
int sum = 0;
for (int j = 0; j < Months; j++)
{
cout << "Enter the sales of " << months[j] << ": ";
cin >> sale[i][j];
sum += sale[i][j];
} cout << "Sales for this year: "
<< sum << endl << endl;
}
return 0;
}*/
//question 7
/*struct car {
string name;
int year;
};
int main()
{
cout << "How many cars do you wish to catalog? ";
int num;
(cin >> num).get();
car* ps = new car[num];
for (int i = 0; i < num; ++i)
{
cout << "Car #" << i + 1 << ":\n";
cout << "Please enter the make: ";
getline(cin, ps[i].name);
cout << "Please enter the year made: ";
(cin >> ps[i].year).get();
}
cout << "Here is your collection:\n";
for (int i = 0; i < num; ++i)
cout << ps[i].year << " " << ps[i].name << endl;
delete[] ps;
return 0;
}*/
//question 8
/*int main()
{
char word[20];
int sum = 0;
cout << "Enter words (to stop,type the word done):\n";
cin >> word;
while (strcmp(word, "done"))
{
sum++;
cin >> word;
}
cout << "You entered a total of " << sum << " words.\n";
return 0;
}*/
//question 9
/*int main()
{
string word;
int sum = 0;
cout << "Enter words (to stop, type the word done):\n";
cin >> word;
while (word != "done")
{
sum++;
cin >> word;
}
cout << "You entered a total of " << sum << " words.\n";
return 0;
}*/
//question 10
/*int main()
{
cout << "Enter number of rows:";
int num;
cin >> num;
for (int i = 0; i < num; i++)
{
for (int j = num - i; j > 1; j--)
cout << ".";
for (int k = 0; k <= i; ++k)
cout << "*";
cout << endl;
}
return 0;
}*/

 

 

转载地址:https://blog.csdn.net/yukinoai/article/details/79934454 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:代数,几何及微积分之间的关系
下一篇:C++Primer Plus笔记——第四章 复合类型及课后编程练习答案

发表评论

最新留言

不错!
[***.144.177.141]2024年04月26日 20时58分38秒