第05章 循环和关系表达式

<c++ primer plus>第六版

5 循环和关系表达式

5.1 for循环

语法

for (initialization; test-expression; update-expression)
{
    body
}

5.2 while循环

while (test_condition)
{
    body
}
#include<ctime>
using namespace std;
clock_t delay = 6*CLOCKS_PER_SEC; //6 seconds
clock_t start = clock(); //current time
while(clock()-start < delay) //wait for 6 seconds.

类型别名,

语法: typedef typeName aliasName;
例  : typedef char BYTE;
例  : typedef char* byte_pointer; //pointer to char type

5.3 do-while循环

特点是循环体至少执行一次.

do
{
    body
} while(test-condition); //最后有分号

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

#include<iostream>
int main()
{
    using namespace std;

    double prices[5] = {4.99, 10.99, 6.87, 7.99, 8.49};

    for(double x:prices) {//x依次表示数组的各元素
        cout << x << std::endl;
    }

    for (double &x: prices) {//x是个引用, 可以通过x修改数组内容
        x *= 0.80; //修改数组元素
    }

    for (int x: {3,5,2,8,6}) { //循环对象是初始化列表
        cout << x << " ";
    }
    cout << endl;
}

老的for循环

int i;
for (i=0;i<10; i++){
    printf("%d", i);
}

5.5 循环和文本输入

5.5.1 使用原始的cin进行输入

cin会忽略空格和换行符.

5.5.2 使用cin.get(char)

5.5.3 文件尾条件

5.6 嵌套循环和二维数组

int maxtemps[4][5]; //maxtemps由4个元素组成, 每个元素都是一个整数数组.

int maxtemps[4][5] = //初始化2维数组
{
    {96, 100, 87, 101, 105}, // value for maxtemps[0]
    {96,  98, 91, 107, 104}, // value for maxtemps[1]
    {97, 101, 93, 108, 107}, // value for maxtemps[2]
    {98, 103, 95, 109, 108}  // value for maxtemps[3]
};
posted @ 2022-07-10 10:59  编程驴子  阅读(33)  评论(0编辑  收藏  举报