再读《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.
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;
}
- 执行 statement1, 只执行1次;
- 执行 statement2, 判断是否为真,如果为真:则执行3步骤,如果为假:则执行5步骤
- 执行 statement4,
- 执行 statement3, 跳回执行步骤2
- 退出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();}
- 再读《The C Programming language》 - 第一章 1.3 for语句
- 再读《The C Programming language》 - 第一章 1.1 入门
- 再读《The C Programming language》 - 第一章 1.4 字符常量
- 再读《The C Programming Language》 - 第一章 1.5 字符输入输出
- 再读《The C Programming Language》 - 第一章 1.6 数组
- 再读《The C Programming Language》 - 第一章 1.7 函数
- 再读《The C Programming Language》 第一章 1.9 字符数组
- 再读《The C Programming language》 - 题记
- 再读《The C Programming language》 - 第一章 1.2 变量和算术表达式
- 再读《The C Programming Language》 第一章 1.10 外部变量和作用域
- 再读《The C Programming Language》 第二章 2.1 变量类型
- 再读《The C Programming Language》 第二章 2.2 运算符
- 再读《The C Programming Language》 第二章 2.3 表达式
- 再读《The C Programming Language》 第二章 2.4 练习汇总
- 《The C Programming Language》第一章读书笔记
- The C programming language --第一章 基本概念读书笔记
- The C Programming Language 第一章导言 读书笔记
- notes for the c programming language
- 集合框架源码分析六之堆结构的实现(PriorityQueue)
- std::string 线程安全
- 首选项中字体,颜色等属性的存取
- websphere 修改 server 的http服务的端口号
- MONGODB Best Practices
- 再读《The C Programming language》 - 第一章 1.3 for语句
- 垃圾回收机制
- Spring AOP
- 一些简单的算法
- 类风格(class style)
- Effective C++学习笔记 (5)
- tomcat 配置方法
- Effective C++学习笔记 (6)
- hdu 1850 Being a Good Boy in Spring Festival(尼姆博弈加强)