Exercise 1-5. Modify the temperature conversion program to print the table in reverse order, that is, from 300 degrees to 0.
作者要求我们反转华氏-摄氏转换表,从300华氏度开始向下输出。
在这里我们利用 for 循环,初始化条件改成 fahr = UPPER ,循环条件改为 fahr >= LOWER ,步长运算从增加一个 STEP 改成减少一个 STEP 即可。
完整代码如下:
#include <stdio.h>
#define LOWER 0 // lower limit of table
#define UPPER 300 // uppper limit
#define STEP 20 // step size
// print Fahrenheit-Celsius table
main() {
int fahr;
for(fahr = UPPER; fahr >= LOWER; fahr = fahr - STEP)
printf("%3d %6.1f\n", fahr, (5.0 /9.0) * (fahr - 32));
}
输出结果如下:
> ./Exercise1_5
300 148.9
280 137.8
260 126.7
240 115.6
220 104.4
200 93.3
180 82.2
160 71.1
140 60.0
120 48.9
100 37.8
80 26.7
60 15.6
40 4.4
20 -6.7
0 -17.8
备注:笔者认为编译的时候把 -o 指令放到最后是一个好习惯:
gcc Exercise1_5.c -o Exercise1_5
因为今天笔者不小心运行了下面的命令:
gcc -o Exercise1_5.c
然后,源代码文件就无了。感觉真棒。