六、C控制语句: 循环
1. 再探 while 循环
/* summing.c -- 根据用户键入的整数求和 */
#include <stdio.h>
int main(void)
{
long num;
long sum = 0L; /* 把 sum 初始化为0 */
int status;
printf("Please enter an integer to be summed ");
printf("(q to quit): ");
status = scanf("%ld", &num);
while (status == 1) /* == 的意思是“等于” */
{
sum = sum+ num;
printf("Please enter next integer (q to quit):");
status = scanf("%ld", &num);
}
printf("Those integers sum to %ld.\n", sum);
return 0;
}
//Please enter an integer to be summed (q to quit): 44
//Please enter next integer (q to quit):33
//Please enter next integer (q to quit):88
//Please enter next integer (q to quit):121
//Please enter next integer (q to quit):q
//Those integers sum to 286.
1.1 程序注释
获得第1个用于测试的值
当测试为真时
处理值
获取下一个值
1.2 C风格读取循环
status = scanf("ld", &num);
while (status == 1)
{
/* 循环行为 */
status = scanf("%ld", &num);
}
可以替换:
while (scanf("ld", &num) == 1)
{
/* 循环行为 */
}
意为:
当获取值和判断值都成功
处理该值
2. while 语句
while循环的通用形式如下:
while (expression)
statement
2.1 终止 while 循环
index = 1;
while (index < 5)
printf("Good morning!\n");
//程序将打印无数次Good morning!
2.2 何为终止循环
// when.c -- 何时退出循环
#include <stdio.h>
int main(void)
{
int n = 5;
while (n < 7) // 第 7 行
{
printf("n = %d\n", n);
n++; // 第 10 行
printf("Now n = %d\n", n); // 第 11 行
}
printf("The loop has finished.\n");
return 0;
}
//n = 5
//Now n = 6
//n = 6
//Now n = 7
//The loop has finished.
2.3 while: 入口条件循环
//进入循环有条件
index = 10;
while (index++ < 5)
printf("Have a fair day or better.\n");
//第一行改为:
//index = 3;
2.4 语法要点
■使用while时,要牢记一点:只有在测试条件后面的单独语句(简单语句或复合语句)才是循环部分。
/* whilel.c -- 注意花括号的使用 */
/* 糟糕的代码创建了一个无限循环 */
#include <stdio.h>
int main(void)
{
int n = 0;
while (n < 3)
printf("n is %d\n", n);
n++;
printf("That's all this program does.\n");
return 0;
}
//n is 0
//n is 0
//n is 0
//n is 0
//...
//由于while没加花括号,while只识别了printf,n++不在循环中,所有n的值一直是0,无限循环打印。
■要注意放置分号的位置
/* while2.c -- 注意花括号的使用 */
#include <stdio.h>
int main(void)
{
int n = 0;
while (n++ < 3); /* 第 7 行 */
printf("n is %d\n", n); /* 第 8 行 */
printf("That's all this program does.\n");
return 0;
}
//n is 4
//That's all this program does
//分号使用不当
while (scanf("%d", &num) == 1)
; /* 跳过整数输入 */
//为了提高代码的可读性,应该让这个分号独占一行