第5章 循环和关系表达式

    xiaoxiao2023-10-01  146

    for循环

    表达式和语句

    递增运算符和递减运算符:++和--

    组合赋值运算符

    复合语句(语句块)

    逗号运算符

    关系运算符:>  >= == <= < !=

    while循环

    typedef工具

    do while循环

    字符输入方法get()

    文件尾条件

    嵌套循环和二维数组

     

    5.1 for循环

    // forloop.cpp -- introducing the for loop #include <iostream> int main() { using namespace std; int i; // create a counter // initialize; test ; update for (i = 0; i < 5; i++) cout << "C++ knows loops.\n"; cout << "C++ knows when to stop.\n"; // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ forloop.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out C++ knows loops. C++ knows loops. C++ knows loops. C++ knows loops. C++ knows loops. C++ knows when to stop.

    5.1.1 for循环的组成部分

    // num_test.cpp -- use numeric test in for loop #include <iostream> int main() { using namespace std; cout << "Enter the starting countdown value: "; int limit; cin >> limit; int i; for (i = limit; i; i--) // quits when i is 0 cout << "i = " << i << "\n"; cout << "Done now that i = " << i << "\n"; // cin.get(); // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ num_test.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Enter the starting countdown value: 4 i = 4 i = 3 i = 2 i = 1 Done now that i = 0

    // express.cpp -- values of expressions #include <iostream> int main() { using namespace std; int x; cout << "The expression 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; /// cin.get(); return 0; } // express.cpp -- values of expressions #include <iostream> int main() { using namespace std; int x; cout << "The expression 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; /// cin.get(); return 0; }

    5.1.2 回到for循环

    // formore.cpp -- more looping with for #include <iostream> const int ArSize = 16; // example of external declaration int main() { 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++) std::cout << i << "! = " << factorials[i] << std::endl; // std::cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ formore.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 11! = 39916800 12! = 479001600 13! = 6227020800 14! = 87178291200 15! = 1307674368000

    5.1.3 修改步长

    // bigstep.cpp -- count as directed #include <iostream> int main() { using std::cout; // a using declaration using std::cin; using std::endl;; 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; // cin.get(); // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ bigstep.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Enter an integer: 12 Counting by 12s: 0 12 24 36 48 60 72 84 96

    5.1.4 使用for循环访问字符串

    // forstr1.cpp -- using for with a string #include <iostream> #include <string> 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"; // cin.get(); // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ forstr1.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Enter a word: animal lamina Bye.

    5.1.5 递增运算符(++)和递减运算符(--)

    // plus_one.cpp -- the increment operator #include <iostream> int main() { using std::cout; int a = 20; int b = 20; cout << "a = " << a << ": b = " << b << "\n"; cout << "a++ = " << a++ << ": ++b = " << ++b << "\n"; cout << "a = " << a << ": b = " << b << "\n"; // std::cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ plus_one.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out a = 20: b = 20 a++ = 20: ++b = 21 a = 21: b = 21 int y = ++x; //change x, then assign to y int y = x++; //assign to y, then change z

    5.1.6 副作用和顺序点

    语句中的分号是一个顺序点

     

    5.1.7 前缀格式和后缀格式

    5.1.8 递增/递减运算符和指针

    5.1.9 组合赋值运算符

    5.1.10 复合语句(语句块)

    // block.cpp -- use a block statement #include <iostream> int main() { using namespace std; cout << "The Amazing Accounto will sum and average "; 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++) { // block starts here cout << "Value " << i << ": "; cin >> number; sum += number; } // block ends here cout << "Five exquisite choices indeed! "; cout << "They sum to " << sum << endl; cout << "and average to " << sum / 5 << ".\n"; cout << "The Amazing Accounto bids you adieu!\n"; // cin.get(); // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ block.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out The Amazing Accounto will sum and average five numbers for you. Please enter five values: Value 1: 1942 Value 2: 1948 Value 3: 1957 Value 4: 1974 Value 5: 1980 Five exquisite choices indeed! They sum to 9801 and average to 1960.2. The Amazing Accounto bids you adieu!

    5.1.11 其他语法技巧--逗号运算符

    // forstr2.cpp -- reversing an array #include <iostream> #include <string> 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) { // start block temp = word[i]; word[i] = word[j]; word[j] = temp; } // end block cout << word << "\nDone\n"; // cin.get(); // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ forstr2.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Enter a word: stressed desserts Done

    5.1.12 关系表达式

    5.1.13 赋值、比较和可能犯的错误

    // equal.cpp -- equality vs assignment #include <iostream> 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"; // Warning: you may prefer reading about this program // to actually running it. cout << "Doing it dangerously wrong:\n"; for (i = 0; quizscores[i] = 20; i++) cout << "quiz " << i << " is a 20\n"; // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ equal.cpp equal.cpp:16:31: warning: using the result of an assignment as a condition without parentheses [-Wparentheses] for (i = 0; quizscores[i] = 20; i++) ~~~~~~~~~~~~~~^~~~ equal.cpp:16:31: note: place parentheses around the assignment to silence this warning for (i = 0; quizscores[i] = 20; i++) ^ ( ) equal.cpp:16:31: note: use '==' to turn this assignment into an equality comparison for (i = 0; quizscores[i] = 20; i++) ^ == 1 warning generated.

    5.1.14 C-风格字符串的比较

    word == "mate" 引号括起的字符串常量是地址 C++将C-风格视为地址 strcmp函数,可以是指针,字符串常量或字符数组名 // compstr1.cpp -- comparing strings using arrays #include <iostream> #include <cstring> // prototype for strcmp() 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; // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ compstr1.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out ?ate aate bate cate date eate fate gate hate iate jate kate late After loop ends, word is mate

    5.1.15 比较string类字符串

    string类重载运算符!=的方式:至少有一个操作数为string对象,另一个操作数可以是string类对象,也可以是C_风格字符串。 // compstr2.cpp -- comparing strings using arrays #include <iostream> #include <string> // string class 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; // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ compstr2.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out ?ate aate bate cate date eate fate gate hate iate jate kate late After loop ends, word is mate

    5.2 while循环

    // while.cpp -- introducing the while loop #include <iostream> 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; // start at beginning of string while (name[i] != '\0') // process to end of string { cout << name[i] << ": " << int(name[i]) << endl; i++; // don't forget this step } // cin.get(); // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ while.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Your first name, please: Muffy Here is your name, verticalized and ASCIIized: u: 117 f: 102 f: 102 y: 121

    5.2.1 for与while

    5.2.2 等待一段时间:编写延时循环

    // waiting.cpp -- using clock() in a time-delay loop #include <iostream> #include <ctime> // describes clock() function, clock_t type int main() { using namespace std; cout << "Enter the delay time, in seconds: "; float secs; cin >> secs; clock_t delay = secs * CLOCKS_PER_SEC; // convert to clock ticks cout << "starting\a\n"; clock_t start = clock(); while (clock() - start < delay ) // wait until time elapses ; // note the semicolon cout << "done \a\n"; // cin.get(); // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Enter the delay time, in seconds: 5 starting done

    5.3 do while循环

    // dowhile.cpp -- exit-condition loop #include <iostream> int main() { using namespace std; int n; cout << "Enter numbers in the range 1-10 to find "; cout << "my favorite number\n"; do { cin >> n; // execute body } while (n != 7); // then test cout << "Yes, 7 is my favorite.\n" ; // cin.get(); // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ dowhile.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Enter numbers in the range 1-10 to find my favorite number 9 5 7 Yes, 7 is my favorite.

    5.4 基于范围的for循环(C++11)

    5.5 循环和文本输入

    5.5.1 使用原始的cin进行输入

    // textin1.cpp -- reading chars with a while loop #include <iostream> int main() { using namespace std; char ch; int count = 0; // use basic input cout << "Enter characters; enter # to quit:\n"; cin >> ch; // get a character while (ch != '#') // test the character { cout << ch; // echo the character ++count; // count the character cin >> ch; // get the next character } cout << endl << count << " characters read\n"; // get rid of rest of line // while (cin.get() != '\n') // ; //cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ textin1.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Enter characters; enter # to quit: see ken run#really fast seekenrun 9 characters read cin将忽略空格和换行符,因此输入的空格没有回显,被包括在计数内 进一步,发送给cin的输入被缓冲,用户只有按下回车键后,他输入的内容才会被发送给程序。 这就是运行程序时,可以在#后面输入字符的原因,按下回车键后,整个字符序列将被发送给程序,但程序在遇到#后结束对输入的处理。

    5.5.2 使用cin.get(char)进行补救

    // textin2.cpp -- using cin.get(char) #include <iostream> int main() { using namespace std; char ch; int count = 0; cout << "Enter characters; enter # to quit:\n"; cin.get(ch); // use the cin.get(ch) function while (ch != '#') { cout << ch; ++count; cin.get(ch); // use it again } cout << endl << count << " characters read\n"; // get rid of rest of line // while (cin.get() != '\n') // ; //cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ textin2.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Enter characters; enter # to quit: Did you use a #2 pencil? Did you use a 14 characters read

    5.5.3 使用哪一个cin.get()

    char name[ArSize]; cout << "Enter your name:\n"; cin.get(name, ArsSize).get(); cin.get(name, ArSize); cin.get(); char ch; cin.get(ch);

    5.5.4 文件尾条件

    如果输入来自文件,可以使用功能更更大的技术--检测文件尾(EOF) 首先很多操作系统,都支持重定向,允许用文件替换键盘输入。 < 重定向运算符 操作系统支持用键盘来模拟文件尾条件 Ctrl + D(Unix)Crtl + Z(Windows)

    // textin3.cpp -- reading chars to end of file #include <iostream> int main() { using namespace std; char ch; int count = 0; cin.get(ch); // attempt to read a char while (cin.fail() == false) // test for EOF #while (!cin.fail()) { cout << ch; // echo character ++count; cin.get(ch); // attempt to read another char } cout << endl << count << " characters read\n"; return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ textin3.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out The green bird sings in the winter. The green bird sings in the winter. ^Z [1]+ Stopped ./a.out

    5.5.5 另一个cin.get()版本

    // textin4.cpp -- reading chars with cin.get() #include <iostream> int main(void) { using namespace std; int ch; // should be int, not char int count = 0; while ((ch = cin.get()) != EOF) // test for end-of-file { cout.put(char(ch)); ++count; } cout << endl << count << " characters read\n"; return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ textin4.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out The sullen mackerel sulks in the shadowy shallows The sullen mackerel sulks in the shadowy shallows ^Z [2]+ Stopped ./a.out

    5.6 嵌套循环和二维数组

    5.6.1 初始化二维数组

    5.6.2 使用二维数组

    // nested.cpp -- nested loops and 2-D array #include <iostream> const int Cities = 5; const int Years = 4; int main() { using namespace std; const char * cities[Cities] = // array of pointers { // to 5 strings "Gribble City", "Gribbletown", "New Gribble", "San Gribble", "Gribble Vista" }; int maxtemps[Years][Cities] = // 2-D array { {96, 100, 87, 101, 105}, // values for maxtemps[0] {96, 98, 91, 107, 104}, // values for maxtemps[1] {97, 101, 93, 108, 107}, // values for maxtemps[2] {98, 103, 95, 109, 108} // values for maxtemps[3] }; 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; } // cin.get(); return 0; } [wlsh@wlsh-MacbookPro] chapter_5$ g++ nested.cpp [wlsh@wlsh-MacbookPro] chapter_5$ ./a.out Maximum temperatures for 2008 - 2011 Gribble City: 96 96 97 98 Gribbletown: 100 98 101 103 New Gribble: 87 91 93 95 San Gribble: 101 107 108 109 Gribble Vista: 105 104 107 108

     

    5.7 总结

     

     

     

     

     

     

     

     

     

     

    最新回复(0)