1.2 变量与算术表达式
使用公式$°C= \frac{5}{9}(°F-32)$打印下列华氏温度与摄氏温度的对照表:
0 -1
20 -6
40 4
60 15
80 26
100 37
120 48
140 60
160 71
180 82
200 93
220 104
240 115
260 126
280 137
300 148
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <stdio.h> int main() { int celsius; int lower,upper,step,fahr; lower = 0; upper = 300; step = 20; fahr = lower;
printf("%10s\t%10s\n","华氏温度","摄氏温度"); while(fahr <= upper) { celsius = 5 * (fahr - 32) / 9; printf("%10d\t%10f\n",fahr,celsius); fahr = fahr + step; } }
|
注意:此处不用(5/9)*(fahr-32)是因为5除以9先会转化成int型,所以最后再除以9,最好是把温度定义成float型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <stdio.h>
int main() { float celsius; int lower,upper,step,fahr;
lower = 0; upper = 300; step = 20;
fahr = lower; printf("%10s\t%10s\n"," 华氏温度","摄氏温度"); for(; fahr <= 300; fahr += step) { celsius = 5.0 * (fahr - 32) / 9.0; printf("%10d\t%10f\n",fahr,celsius); } }
|