while 也是一种入口条件循环,只有测试条件和循环体:
while (/* 测试条件 */ ) {//循环体}
5.2.1 for 与 while
本质上这两个循环是相同的。以下代码等价:
//以下等价for (int i = 0; i < 5; ++i) {cout << i << endl;}int i = 0;while (i < 5) {cout << i << endl;++i;}//以下也等价while (i < 0) {cout << i << endl;}for (; i < 0) {cout << i << endl;}
通常,知道循环次数的用 for,无法预知循环次数的用 while。
5.2.2 编写延时循环
这时就得用系统时钟来完成。clock() 函数返回程序开始执行后所用的系统时间。
但是,返回时间的单位不一定是秒,类型有的系统是 long,有的是 unsigned long。头文件 ctime(较早的是 time.h)解决了这个问题。它定义了一个符号常量 CLOCKS_PER_SEC,表示每秒钟包含的系统时间单位数。另外,ctime 将 clock_t 作为 clock() 返回类型的别名,编译器会将它转换成合适的类型。
示例:
#include <iostream>#include <ctime>using namespace std;int main(){cout << "Enter the delay time, in seconds:";float secs;cin >> secs;clock_t delay = secs * CLOCKS_PER_SEC;clock_t start = clock();while (clock() - start < delay) {//...}cout << done << endl;return 0;}
类型别名 C++ 为类型建立别名的两种方式:
- 使用预处理器:#define BYTE char。BYTE 是别名。
- 使用 typedef 关键字:typedef char BYTE。BYTE 是别名。
推荐使用第二种,typedef 不会创建新类型,只是为已有类型建立一个新名字。
