易错点:for循环中循环变量的更新所带来的问题

易错点:for循环中循环变量的更新所带来的问题标签:C语言 for循环 易错点by 小威威1.for循环的介绍for循环的格式如下: for (表达式1;表达式2;表达式3) 其中,表达式1指初始化表达式,表达式2指循环条件表达式,表达式3指循环变量更新表达式。表达式1的位置可为多个赋值表达式,各个表达式之间用逗号隔开,如:for (i = 0, j = 0; i < 100; i++) {
摘要由CSDN通过智能技术生成

易错点: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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值