Jump to: navigation, search

The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 1.15 on page 27

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



Solution by Liron Abutbul

/**
 * Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.
*/

#include <stdio.h>

#define LOWER 0 // lower limit of the temperature table
#define UPPER 300 // upper limit of the temperature table
#define STEP 20 // step size

float fahr_to_celsius(float fahr);

int main(void) {
    int fahr = LOWER;

    printf("Fahrenheit Celsius\n");
    while (fahr <= UPPER) {
        printf("%10d %7.1f\n", fahr, fahr_to_celsius(fahr));
        fahr = fahr + STEP;
    }

    return 0;
}

float fahr_to_celsius(float fahr) {
    return (5.0 / 9.0) * (fahr - 32.0);
}
Fahrenheit Celsius
         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

Solution by Vidhan Gupta

/* Rewrite the temperature conversion program of Section 1.2 to use a function for conversion. */

#include <stdio.h>

#define UPPER 300
#define LOWER 0
#define STEP 20

float ftoC(int f);

int main()
{
    int i;
    for (i = LOWER; i <= UPPER; i = i + STEP)
        printf("%3d, %6.1f\n", i, ftoC(i));
        
    return 0;
}

float ftoC(int fahr)
{
    return 5.0 / 9.0 * (fahr - 32);
}
OUTPUT:
  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


Solution by Richard Heathfield

#include <stdio.h>

float FtoC(float f)
{
  float c;
  c = (5.0 / 9.0) * (f - 32.0);
  return c;
}

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

  lower = 0;
  upper = 300;
  step = 20;

  printf("F     C\n\n");
  fahr = lower;
  while(fahr <= upper)
  {
    celsius = FtoC(fahr);
    printf("%3.0f %6.1f\n", fahr, celsius);
    fahr = fahr + step;
  }
  return 0;
}

Solution by Octavian

#include <stdio.h>

int fahr_celsius(int fahr);

int main(void)
{
        int i;

        for (i = 0; i <= 300; i = i + 20)
                printf("%d fahr %6d celsius \n", i, fahr_celsius(i));
        return 0;
}

int fahr_celsius(int t)
{
        int celsius;
        celsius = (5.0 / 9) * (t - 32);
        return celsius;
}
Personal tools