title: 第六章 C控制语句:循环
author: HardyDragon
tags: C Notes
第六章 C控制语句:循环
6.1 再探while循环
程序注释
C风格读取循环
6.2 while语句
6.2.1 终止while循环
何时终止循环
while:入口条件循环
语法要点
6.3 用关系运算符和表达式比较大小
6.3.1 什么是真
6.3.2 其他真值
6.3.3 真值的问题
6.3.4 新的_Bool 类型
6.3.5 优先级和关系运算符
6.4 不确定循环和计数循环
6.5 for循环
6.6 其他赋值运算符: += 、-=、*=、/=、%=
6.7 逗号运算符
6.8 出口条件循环:do while
6.9 如何选择循环
6.10 嵌套循环
6.10.1 程序分析
6.10.2 嵌套变式
6.11 数组简介
6.12 使用函数返回值的循环示例
6.12.1 程序分析
6.12.2 使用带返回值的函数
6.13 关键概念
6.14 本章小结
6.15 复习题
6.16 编程练习
6.1 再探while循环
// summing.c -- 根据用户输入的整数求和
#include <stdio.h>
int main(int argc, char const *argv[])
{
long num;
long sum = 0L;
int status;
printf("please enter an integer to be sum(Q to quit):\n");
status = scanf("%ld", &num);
while (status == 1)
{
/* code */
sum = sum + num;
printf("please enter an integer to be sum(Q to quit):\n");
status = scanf("%ld", &num);
}
printf("sum is %ld\n",sum);
return 0;
}
result:
please enter an integer to be sum(Q to quit):
44
please enter an integer to be sum(Q to quit):
33
please enter an integer to be sum(Q to quit):
88
please enter an integer to be sum(Q to quit):
121
please enter an integer to be sum(Q to quit):
q
sum is 286
该程序使用long类型以存储更大的整数,尽管C编译器会把0自动转换为合适的类型,但是为了保持程序的一致性,把sum初始化为0L,而不是0(int类型的0);
回顾一下,scanf() 的返回值若成功读取一个整数,就将读取的数放入变量,并返回1。如果输入的类型匹配失败就返回0;如果scanf() 在转换值前出现了问题会返回一个特殊值EOF(-1),这个也会导致循环终止。
因为while循环时入口条件循环,程序在进入循环体前必须获取输入的数据并检查status的值,所以while前面要有一个scanf() ,要让循环继续执行,在循环内需要一个读取数据的语句,这样程序才能获取下一个status的值,所以scanf() 函数末尾还要有一个scanf() 它为下一次迭代做好了准备。
-
C风格的读取循环
status = scanf("%ld", &num); while (status == 1) { /* code */ status = scanf("%ld",&num); }
以上读取循环输入的代码可以写的更简洁:(相当于省略中间变量status)
while (scanf("%ld", &num) == 1) { /* code */ }
6.2 while语句
关于终止while循环要注意其条件语句,最小负值减1一般会得到最大值,最大值加1会得到一个负值。
注意while 的分号;位置,while也是一个单独语句。
// while2.c -- 注意分号位置
#include<stdio.h>
int main(int argc, char const *argv[])
{
int n=0;
while (n++<3);
printf("n is %d \n",n);
return 0;
}
result:
n is 4
利用这种空语句的循环,可以做到:跳过第一个非空白字符或数字。
while (scanf("%d", &num) == 1)
;
// 跳过整数输入
只要输入一个整数,那么条件为真,继续循环读取输入;注意分号最好单独放一行便于理解,但是可以使用continue来更好的处理这种奇葩的情况。
6.3 用关系运算符和表达式比较大小
!= 不等于
// cmpflt.c -- 浮点数比较
#include <math.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
const double ANSER