HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Using functions to separate code for Fahrenheit to celsius conversion

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conversionseparatefahrenheitforusingcodefunctionscelsius

Problem

I'm relatively new to programming, and I've been wondering about a problem such as this. How can I think about decomposing the code into its constituent functions? I went the simplest route I could, just putting the formula in its own function. I believe this makes the code more readable, but there's also a part of me that wants to put the while loop into a function as well.

Is there a good rule of thumb for separating my code into functions?

#include 

int fahr_to_celsius(int f);

/* print Farhenheit-Celsius table
   for fahr = 0, 20, ..., 300 *;
   use a function for conversion */
int main(void)
{
  int fahr, celsius;
  int lower, upper, step;

  lower = 0; /* lower limit of the temperature table */
  upper = 300; /* upper limit */
  step = 20; /* step size */

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

int fahr_to_celsius(int fahr)
{
  int celsius = 5 * (fahr-32) / 9;
  return celsius;
}

Solution

In a more complex program I would probably extract the loop, but I think this is actually pretty good as is. Your main routine reads very well and describes precisely what this program does. You separated the concerns of performing the conversion and displaying the results and your conversion method performs a single task. I agree that extracting it was a wise choice.

You'll often hear the phrase


A method should do one thing, and do it well.

You nailed the first part, but I'm not so sure about the second. I guess it depends on how accurate you need it to be.

int celsius = 5 * (fahr-32) / 9;


This is very likely to be a non-integer number before you cast it. C casts from floating point to integer via truncation. This means that you're always "rounding" the result down. I doubt that's what you intended. Use the round() method instead for a more accurate result. Or, even better, return a double.

One other thing, don't abbreviate variable names. I understand why you used fahr instead of fahrenheit, but it's a bad habit to get into.

Code Snippets

int celsius = 5 * (fahr-32) / 9;

Context

StackExchange Code Review Q#104089, answer score: 5

Revisions (0)

No revisions yet.