再读《The C Programming language》 - 第一章 1.3 for语句

来源:互联网 发布:js 分享到qq空间 编辑:程序博客网 时间:2024/05/01 23:47

1.3 for语句


for语句是C语言用的最多语句之一,简洁,可读性强~ 是写程序必备之利器也。
首先看看用for语句重写的华氏温度转换为摄氏温度的程序

// main.c// version 5.0 -- for // Print Celsius -> Fahrenheit table// for celsius = 0, 20, ..., 300#include <stdio.h>main(){    int fahr;     for(fahr=0; fahr < 300; fahr+= 20)    {        printf("%3d %6.1f\n",fahr,(5.0 / 9.0) * (fahr - 32));    }    getchar();}


少了好多代码吧~看起来多么简洁明了吧,其实while也可以的只是这里为了突出for的简洁!至于到底用那个好,书中也给出了中肯的建议
The choice between while and for is arbitrary, based on which seems clearer. The for is usually appropriate for loops in 
which the initialization and increment are single statements and logically related, since it is more compact than while and it 
keeps the loop control statements together in one place. 
也有网友给我们做了程序上的分析,有兴趣的可以去看看这篇文章 while与for执行效率对比
,如果兴趣更浓,自己写代码测试下也未尝不可。
当然for语句最基本的知识就是要掌握它的一个执行循序~搞错了就要闹笑话了,当然,有可能会是笔试的题目,千万不可小觑!
for(statement1;statement2;statement3)
{
     statement4;
}
  1. 执行 statement1, 只执行1次;
  2. 执行 statement2, 判断是否为真,如果为真:则执行3步骤,如果为假:则执行5步骤
  3. 执行 statement4,
  4. 执行 statement3, 跳回执行步骤2
  5. 退出for循环


Exercise 1-5. Modify the temperature conversion program to print the table in reverse order, that is, from 300 degrees to 0.

// main.c// version 6.0 -- for // Print Celsius -> Fahrenheit table// for celsius = 300, ...,20,0#include <stdio.h>main(){    int fahr;     for(fahr=300; fahr >= 0; fahr-= 20) /* 只修改了此处 */    {        printf("%3d %6.1f\n",fahr,(5.0 / 9.0) * (fahr - 32));    }    getchar();}