{"content":{"id":522,"title":"K\u0026R Solutions - 1.15","body":"\u003cp\u003e\u003cb\u003eQ:\u003c/b\u003e Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.\u003c/p\u003e\r\n\u003cp\u003e\u003cb\u003eA:\u003c/b\u003e\u003c/p\u003e \r\n\u003cpre\u003e\u003ccode class=\"cpp\"\u003e// Compared with the original, this is much easier to read.\r\n\r\n#include \u0026ltstdio.h\u0026gt\r\n \r\nfloat fahrenheit_to_celsius (float fahr) {\r\n return (5.0/9.0) * (fahr-32.0);\r\n}\r\n\r\nint main(void) {\r\n int lower = 0;\r\n int upper = 300;\r\n int step = 20;\r\n float fahr = lower;\r\n\r\n while (fahr \u003c= upper) {\r\n printf(\"%3.0f %6.1f\\n\", fahr, fahrenheit_to_celsius(fahr));\r\n fahr = fahr + step;\r\n }\r\n\r\n return 0;\r\n}\u003c/code\u003e\u003c/pre\u003e\r\n\u003cpre\u003e\u003ccode class=\"lisp\"\u003e 0 -17.8\r\n 20 -6.7\r\n 40 4.4\r\n 60 15.6\r\n 80 26.7\r\n100 37.8\r\n120 48.9\r\n140 60.0\r\n160 71.1\r\n180 82.2\r\n200 93.3\r\n220 104.4\r\n240 115.6\r\n260 126.7\r\n280 137.8\r\n300 148.9\r\n\u003c/code\u003e\u003c/pre\u003e","publication_date":"2019-03-08T00:00:00.000Z","created_at":"2019-02-05T18:34:52.000Z","updated_at":"2019-02-12T20:19:30.000Z","user_id":1,"rating":null},"tags":"\u003ca class=\"changeable-title\" href=\"/q?tag=k%26r\"\u003ek\u0026amp;r\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=programming\"\u003eprogramming\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=answers\"\u003eanswers\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=c\"\u003ec\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=unix\"\u003eunix\u003c/a\u003e"}

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