while 循环介绍
while 循环的作用:Repeats a block of statements while a condition is True or until a condition becomes True.
while 循环的通用形式:
while (condition)
statement
statement 可以是以分号结尾的简单语句, 也可以是用花括号括起来的复合语句.
复合语句和简单语句从语法上来说都算是一条单独语句.
condition 是测试表达式.
condition:Numeric or string expression that is True or False. If condition is Null, condition is treated as False.
statements:One or more statements that are repeated while or until condition is True.
while 循环使用的是入口条件的有条件循环, 所谓 “有条件” 指的是语句部分的执行取决于测试表达式描述的条件. 该表达式是一个入口条件, 因为必须满足条件才能进入循环体.
不确定循环 (indefinite loop) 是指在测试表达式为假之前, 预先不知道要执行多少次循环.
计数循环 (counting loop) 是指在执行循环之前就知道要重复执行多少次.
示例程序:
用户键入一系列整数, 程序计算这些整数的和并进行输出.
#include<stdio.h>
int main(void)
{
long num;
long sum = 0L;
int status;
printf("Enter an integer to be summed (q to quit): ");
while (scanf("%d", &num))
{
sum += num;
printf("Enter next integer (q to quit): ");
}
printf("Those integers sum to %ld.\n", sum);
return 0;
}
结果:
Enter an integer to be summed (q to quit): 3
Enter next integer (q to quit): 4
Enter next integer (q to quit): 5
Enter next integer (q to quit): q
Those integers sum to 12.
示例程序:
#include <stdio.h>
#define ADJUST 7.31 // 字符常量
int main(void)
{
const double SCALE = 0.333; // const 常量
double shoe, foot;
printf("Shoe size (men's) foot length\n");
shoe = 3.0;
while (shoe < 18.5) // while 循环开始
{ // 块开始
foot = SCALE * shoe + ADJUST;
printf("%10.1f %15.2f inches\n", shoe, foot);
shoe=shoe+1.0;
} // 块结束
printf("If the shoe fits, wear it.\n");
return 0;
}
结果:
Shoe size (men's) foot length
3.0 8.31 inches
4.0 8.64 inches
5.0 8.97 inches
6.0 9.31 inches
7.0 9.64 inches
8.0 9.97 inches
9.0 10.31 inches
10.0 10.64 inches
11.0 10.97 inches
12.0 11.31 inches
13.0 11.64 inches
14.0 11.97 inches
15.0 12.31 inches
16.0 12.64 inches
17.0 12.97 inches
18.0 13.30 inches
If the shoe fits, wear it.
程序示例:
#include<stdio.h>
int main(void)
{
const int NUMBER = 10;
int count = 1; // 初始化计数器
while (count <= NUMBER) // 计数器和有限值作比较
{
printf("Be my valentine!\n");
count++; // 每次循环计数器递增
}
return 0;
}
结果:
Be my valentine!
Be my valentine!
Be my valentine!
Be my valentine!
Be my valentine!
Be my valentine!
Be my valentine!
Be my valentine!
Be my valentine!
Be my valentine!
这是一个计数循环, 但是定义循环的行为并未组织在一起, 程序的编排不理想.
创建一个计数循环时有三个行为:
- 初始化计数器
- 计数器和有限值作比较
- 每次循环计数器递增
用 while 循环创建计数循环时未能将这三个行为组织在一起.
一种简单的函数头:
while(a)
等价于:
while( a != 0 )
都是 a 不等于 0 时进入循环.
continue 在 while 中的使用
如果 continue 在嵌套循环内, 则只会影响包含该语句的内层循环.
continue 后是执行循环头内的测试表达式.
break 在 while 中的使用
如果 break 在嵌套循环内, 则只会影响包含该语句的内层循环.