K&R Solutions - 1.15

Q: Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.

A:

// Compared with the original, this is much easier to read.

#include <stdio.h>
  
float fahrenheit_to_celsius (float fahr) {
  return (5.0/9.0) * (fahr-32.0);
}

int main(void) {
  int lower = 0;
  int upper = 300;
  int step = 20;
  float fahr = lower;

  while (fahr <= upper) {
    printf("%3.0f %6.1f\n", fahr, fahrenheit_to_celsius(fahr));
    fahr = fahr + step;
  }

  return 0;
}
  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