练习1-4 编写一个程序打印摄氏温度转换为相应华氏温度的转换表。
ChapterOneExerciseFourOne.cpp
cpp
#include <stdio.h>
/* print Celsius-Fahrenheit table
for celsius = 0, 20, ..., 300; floating-point version */
main()
{
float fahr, celsius;
int lower, upper, step;
lower = 0; /* lower limit of temperature table */
upper = 300; /* upper limit */
step = 20; /* step size */
printf("Celsius Fahr\n");
celsius = lower;
while(celsius <= upper){
fahr = (9.0*celsius) / 5.0 + 32.0;
printf("%3.0f %6.1f\n", celsius, fahr);
celsius = celsius + step;
}
}
本程序将输出一个摄氏温度(0~300)到华氏温度的转换表。华氏温度是用以下语句计算得到的:
cpp
fahr = (9.0*celsius) / 5.0 + 32.0;
本题的解题思路与打印华氏温度到摄氏温度的对照表程序(见K&R原著第12页)是相同的。整型变量lower、upper、step分别对应变量celsius的下限、上限、步长。程序先把变量celsius初始化为它的下限,再在while循环中把对应的华氏温度计算出来。然后,程序打印出这组摄氏温度和华氏温度的值,并按步长递增变量celsius的值。while循环将一直执行,直到变量celsius超出其上限为止。