Exercise 1.15. Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.
Let us see the Fahr-to-Celsius program in Section 1.2 first:
#include <stdio.h>
/* print Fahrenheit-Celsius table
for fahr = 0, 20, ..., 300; floating-point version */
main() {
float fahr, celsius;
float lower, upper, step;
lower = 0;
upper = 300;
step = 20;
fahr = lower;
while (fahr <= upper) {
celsius = (5.0 / 9.0) * (fahr - 32.0);
printf("%3.0f %6.1f\n", fahr, celsius);
fahr = fahr + step;
}
}
There are may ways for us to set up functions. For example: one function for table printing and the other for celsius calculation. Or a "big" function including both caculation and printing. Or just a calculation function, and remain the while/for circulation. It depends on your preference. However, I would like the final one and the function will be:
double fahrToCelsius(double fahr) {
return (fahr - 32) * 5.0 / 9.0;
}
Then just remove the celsius calculation in the main() and replace the celsius in printf() by the function calling. We can get the new program with function utilization.
#include <stdio.h>
#define UPPER 300
#define LOWER 0
#define STEP 20
double fahrToCelsius(double fahr);
int main(void) {
double fahr;
for (fahr = LOWER; fahr <= UPPER; fahr += STEP)
printf("%3.0f\t%6.1f\n", fahr, fahrToCelsius(fahr));
return 0;
}
double fahrToCelsius(double fahr) {
return (fahr - 32) * 5.0 / 9.0;
}