Beginner's C shenanigans


Blog What I'm writing The status quo

I'm teaching myself the C language from a variety of sources, including Kernighan and Ritchie's The C Programming Language. I'm up to Exercise 1.4 when I hit the first of what will be many roadblocks wrapping my head around this venerable language.

The exercise asks that you write a small program that converts Celsius into Fahrenheit, which is the flip side of the F → C given in the book.

So I did, using the book's example as an exemplar.

This was my attempt:

#include <stdio.h>

/* print Celsius-Fahrenheit table

for celsius = 0, 20, ..., 300 */
int main(void)
{
    printf("Celsius to Fahrenheit conversion\n");
    
    float fahr, celsius;
    int lower, upper, step;
    
    lower = 0;      /* lower limit of temperature scale */
    upper = 300;    /* upper limit */
    step = 20;      /* step size */

    celsius = lower;
    while (celsius <= upper) {
        fahr = (9.0/5.0) * (celsius + 32.0);
        printf("%3.0f %6.1f\n", celsius, fahr);
        celsius = celsius + step;         
    }
    return 0;
}

When I ran it, I had two nicely formatted tables with a heading, but the Fahrenheit output was exactly twenty degrees higher than what it should be. That is, 0° C was 52° F when it should be 32.

The formula to convert Celsius into Fahrenheit is: °F = °C × (9 ÷ 5) + 32

Note that only the division is between parentheses and that gets operated on according to the order of operations. If you look at my code above, you'll note that I put parentheses about the addition too, which threw the whole thing out.

The correct code is:

#include <stdio.h>

/* print Celsius-Fahrenheit table

for celsius = 0, 20, ..., 300 */
int main(void)
{
    printf("Celsius to Fahrenheit conversion\n");
    
    float fahr, celsius;
    int lower, upper, step;
    
    lower = 0;      /* lower limit of temperature scale */
    upper = 300;    /* upper limit */
    step = 20;      /* step size */

    celsius = lower;
    while (celsius <= upper) {
        fahr = (9.0/5.0) * celsius +32.0;
        printf("%3.0f %6.1f\n", celsius, fahr);
        celsius = celsius + step;         
    }
    return 0;
}

Moral of this story? Simple things will trip you up as effectively as big things.

My journey in C continues, and lesson learned.

©1996-2020 Peter Greenwell Text and images Creative Commons License