【C++】学习笔记十六——while循环

while循环

while循环是没有初始化和更新部分的for循环,他只有测试条件和循环体:

while (test-condition)
        body

程序5.13

#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;
    while (name[i] != '\0')
    {
        cout << name[i] << ": " << int(name[i]) << endl;
        i++;
    }
    cin.get();
    cin.get();
    return 0;
}

这里写图片描述

1. for与while

for和while本质上是相同的:

for (init-expression; test-expression; update-expression)
{
    statement(s)
}

可以改写为:

init-expression;
while (test-expression)
{
    statement(s)
    update-expression;
}

for循环与while循环的差别:

  1. 在for循环中省略测试条件时,将认为条件为true;
  2. 在for循环中,可使用初始化语句声明一个局部变量,但在while循环中不能这样做;
  3. 如果循环体包括continue语句,情况将稍有不同。continue语句将在后面介绍。

通常,程序员使用for循环来为循环技术,因为for循环格式允许将所有相关的信息——初始值、终止值和更新计数器的方法——放在同一个地方。

在无法知道循环将执行的次数时,程序员使用while循环。

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

clock()函数返回程序开始执行后所用的系统时间,但返回的时间单位不一定是秒。

头文件ctime定义了一个符号常量CLOCK_PER_SEC,该常量等于每秒钟包含的系统时间单位数。因此将系统时间除以这个值,可以得到秒数。或者将秒数乘以CLOCK_PER_SEC可以得到以系统时间单位为单位的时间。
另外,ctime将clock_t作为clock()返回类型的别名,这意味着可以将变量声明为clock_t类型,编译器将把他转换为long、unsigned int或者适合系统的其他类型。

程序5.14

#include<iostream>
#include<ctime>
int main()
{
    using namespace std;
    cout << "Enter the deley time, in seconds: ";
    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";
    cin.get();
    cin.get();
    return 0;
}

3. do while循环

do while循环是出口循环,循环将首先执行循环体,然后再判定测试表达式。

do
    body
while (test-expression);

程序5.15

#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;
    } while (n != 7);
    cout << "Yes, 7 is my favorite number.\n";
    cin.get();
    cin.get();
    return 0;
}

这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值