当作复习。。。
(1)将华氏度 换算成 摄氏度,公式:
℃=(5/9)(̧°F-32)
#include <stdio.h> int transformTemprature(int F){ //`C=(5/9)(̧`F-32) return (int)(5 * (F-32) / 9); } int main(){ int lower = 0; int upper = 300; int step = 20; for(int f=lower; f<=upper; f+=step){ printf("%d %d ",f,transformTemprature(f)); } return 0; }
lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ vim Temprature.c lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ cc -std=gnu99 Temprature.c lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ a.out 0 -17 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 修改为 printf("%d %d ",f,transformTemprature(f)); 加入制表符 lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ vim Temprature.c lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ cc -std=gnu99 Temprature.c lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ a.out 0 -17 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 修改为 printf("%3d%3d ",f,transformTemprature(f)); 右对齐 lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ vim Temprature.c lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ cc -std=gnu99 Temprature.c lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ a.out 0 -17 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
(2)为了使精度更高。将变量由int 改为 float
#include <stdio.h> float transformTemprature(int F){ //`C=(5/9)(̧`F-32) return (5.0/9.0) * (F-32.0); } int main(){ float lower = 0; float upper = 300; float step = 20; for(float f=lower; f<=upper; f+=step){ printf("%3.0f%6.1f ",f,transformTemprature(f)); } return 0; }
lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ vim TempratureFloat.c lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ cc -std=gnu99 TempratureFloat.c lenovo-myc@lenovomyc-Lenovo-Product:~/C_test$ a.out 0 -17.8 20 -6.7 40 4.4 60 15.6 80 26.7 100 37.8 120 48.9 140 60.0 160 71.1 180 82.2 200 93.3 220 104.4 240 115.6 260 126.7 280 137.8 300 148.9
(3)去掉多余参数
#include <stdio.h> float transformTemprature(int F){ //`C=(5/9)(̧`F-32) return (5.0/9.0) * (F-32.0); } int main(){ for(int f=0; f<=300; f+=20){ printf("%3d%6.1f ",f,transformTemprature(f)); } return 0; }
(4) 将 幻数 替换为 #define 符号常量
#include <stdio.h> #define LOWWER 0 /* lower limit of table */ #define UPPER 300 /* upper limit */ #define STEP 20 /* step size */ float transformTemperature(int f){ return (5.0/9.0) * (f - 32.0); } /* print Fahrenheit-Celsius table */ int main(){
for(int f=LOWWER; f<=UPPER; f+=STEP){ printf("%3d%6.1f ",f,transformTemperature(f)); } return 0; }