Oct 2, 2015

K & R : Exercise 1.15 - Temperature conversion function

Problem Statement:

Exercise 1-15: Rewrite the temperature conversion program of Section 1.2 to use function for conversion.



Solution:

Question asks conversion formula

c = 5/9 ( f - 32) 

to be converted into a function.



#include <stdio.h>

float fahr_to_celsius(float fahr);

int main()
{
  int fahr, celsius;
  int lower, upper, step;

  lower = 0;   /* lower limit of temp table */
  upper = 300; /* upper limit */
  step = 20;

  fahr = lower;
  while(fahr <= upper) {
    celsius = fahr_to_celsius(fahr);
    printf("%d\t%d\n", fahr, celsius);
    fahr = fahr + step;
  }
  return 0;
}

float fahr_to_celsius(float fahr)
{
  return (5.0 * (fahr - 32) / 9);
}
Output of above program is

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

Next Article -
Previous Article - K & R : Exercise 1.14 - character vertical histogram
All Article - K & R Answer

No comments :

Post a Comment