易错点:for循环中循环变量的更新所带来的问题
标签:C语言 for循环 易错点
by 小威威
1.for循环的介绍
for循环的格式如下:
for (表达式1;表达式2;表达式3)
其中,表达式1指初始化表达式,表达式2指循环条件表达式,表达式3指循环变量更新表达式。表达式1的位置可为多个赋值表达式,各个表达式之间用逗号隔开,如:
for (i = 0, j = 0; i < 100; i++) {
statement;
}
表达式2也可以是多个条件,条件间用逻辑运算符连接,如:
for (i = 0, j = 0; i < 100 && i != 0; i++) {
statement;
}
表达式3也可以是多个变量更新,之间也用逗号隔开,如:
for (i = 0, j = 0; i < 3; i++, j++) {
statement;
}
for循环还有许多灵活的用法,这里就不一一阐述了,以后会系统的总结一下。如今只是对for的结构进行简单介绍以便引入正题。
2.for循环中循环变量的更新所带来的问题
这个问题对于一部分人来说确实不是问题,但我在这方面经常出错,相信也会有人跟我一样的,这里点出来希望大家能注意~
for (int i = 0; i <=10; i++) {
statement;
}
printf("%d\n", i);
此处跳出循环,输出i的值为11.注意,i的值为11不是10~也许这个错误看起来很低端,但是一放到程序中,就不那么低端了,而且还不容易发现。下面我就用实例来说明这一问题。
3.实例
实例一:
Description
You are given a car odometer which displays the miles traveled as an integer. The odometer has a defect, however: it proceeds from the digit 2 to the digit 4 and from the digit 7 to the digit 9, always skipping over the digit 3 and 8. This defect shows up in all positions (the one’s, the ten’s, the hundred’s, etc.). For example, if the odometer displays 15229 and the car travels one mile, odometer reading changes to 15240 (instead of 15230).
Input
Each line of input contains a positive integer in the range 1..999999999 which represents an odometer reading. (Leading zeros will not appear in the input.) The end of input is indicated by a line containing a single 0. You may assume that no odometer reading will contain the digit 3 and 8.
Output