Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Temperature Conversion Code in C: A Practical Guide

· 7 min read · Home Tech

In this article
  1. Why C Is Still a Good Choice for This
  2. The Basic Formulas and the Code
  3. Integer Division: The Classic Mistake
  4. Adding Kelvin and a Menu
  5. Handling User Input Safely
  6. Choosing Between float and double
  7. Common Problems and How to Fix Them
  8. Frequently Asked Questions

Yes, you can write temperature conversion code in C in a few lines using the standard formulas: Celsius to Fahrenheit is F = (C × 9/5) + 32, and Fahrenheit to Celsius is C = (F − 32) × 5/9. The rest of this article covers the exact code, how to handle user input, common pitfalls like integer division, and how to extend the same logic to Kelvin.

Why C Is Still a Good Choice for This

C is a small, fast language with no runtime overhead, which makes it a common first language for learning programming and for embedded systems. A temperature converter is a classic exercise because it uses variables, arithmetic, input/output, and control flow all in one short program. It also forces you to think about data types: a temperature is a floating-point number, but many beginners accidentally use integers and get wrong results. The same formulas appear in countless textbooks and online tutorials, so the code you write in C will look very similar to what you would write in Python, Java, or JavaScript, just with more explicit type declarations and memory management.

The Basic Formulas and the Code

The conversion formulas are fixed and exact. To convert from Celsius to Fahrenheit, multiply by 9, divide by 5, then add 32. To go the other way, subtract 32, multiply by 5, then divide by 9. Here is a complete, working C program that asks the user which direction they want and prints the result:

#include <stdio.h>

int main(void) {
    float temp, result;
    char choice;

    printf("Convert (C)elsius or (F)ahrenheit? ");
    scanf(" %c", &choice);
    printf("Enter temperature: ");
    scanf("%f", &temp);

    if (choice == 'C' || choice == 'c') {
        result = (temp * 9.0 / 5.0) + 32.0;
        printf("%.2f C = %.2f F\n", temp, result);
    } else if (choice == 'F' || choice == 'f') {
        result = (temp - 32.0) * 5.0 / 9.0;
        printf("%.2f F = %.2f C\n", temp, result);
    } else {
        printf("Invalid choice.\n");
    }
    return 0;
}

Notice the 9.0 and 5.0 instead of 9 and 5. That is the single most important detail in this whole article.

Integer Division: The Classic Mistake

If you write temp * 9 / 5 where temp is an int, C performs integer division, which truncates the fractional part. For example, 5 / 2 equals 2, not 2.5. So converting 20 °C would give (20 × 9) / 5 = 180 / 5 = 36, which is correct by luck because 180 is divisible by 5. But converting 21 °C gives 189 / 5 = 37 (truncated) instead of 37.8. The fix is to make at least one operand a floating-point type, either by using 9.0 or by declaring temp as float or double. The same issue appears in the reverse formula. Always test with a value that does not divide evenly, such as 21 °C or 98.6 °F, to confirm your code is correct.

Adding Kelvin and a Menu

Kelvin is another common scale, especially in science. The formulas are: Kelvin to Celsius is C = K − 273.15, and Celsius to Kelvin is K = C + 273.15. You can combine all three scales in one program using a switch statement or a series of if statements. A practical structure is to read the source scale, the target scale, and the value, then compute. For example:

float c_to_f(float c) { return (c * 9.0 / 5.0) + 32.0; }
float c_to_k(float c) { return c + 273.15; }
float f_to_c(float f) { return (f - 32.0) * 5.0 / 9.0; }
float f_to_k(float f) { return c_to_k(f_to_c(f)); }
float k_to_c(float k) { return k - 273.15; }
float k_to_f(float k) { return c_to_f(k_to_c(k)); }

Writing small functions like this keeps the code readable and lets you test each conversion independently. It also makes it easy to add more scales later, such as Rankine, without rewriting the whole program.

Handling User Input Safely

The simple scanf approach works for a learning exercise, but it has limitations. If the user enters a letter instead of a number, scanf fails and leaves the input buffer in a bad state. A more robust program checks the return value of scanf, which returns the number of successfully read items. For example:

if (scanf("%f", &temp) != 1) {
    printf("Invalid number.\n");
    return 1;
}

For a command-line tool, you can also read arguments from argv instead of prompting. That avoids the whole input-buffer problem. For instance, running convert 100 C would parse argv[1] as the number and argv[2] as the scale. This is often cleaner for a utility, but the interactive version is easier for beginners to understand.

Choosing Between float and double

In C, float is typically 32 bits and double is 64 bits. For temperature conversion, float is precise enough for everyday use, but double is the default in many codebases because it avoids subtle rounding errors and matches the precision of the printf default conversions. The difference matters only if you are doing thousands of conversions or working with very small temperature differences. In practice, either works. The key is to be consistent: if you declare the variable as float, use %f in printf; if you use double, use %f as well, but scanf needs %lf for double. Mixing up %f and %lf is a common source of warnings and subtle bugs.

Common Problems and How to Fix Them

  • Wrong results by exactly 32 or 40 degrees: You likely forgot the parentheses. The formula (F − 32) * 5 / 9 is not the same as F − 32 * 5 / 9 because multiplication and division have higher precedence than addition and subtraction.
  • All results are integers: You are using integer variables or integer literals. Change the variable type to float or double and use 9.0 and 5.0.
  • Program skips the temperature input: The scanf(" %c", &choice) leaves a newline in the buffer, and the next scanf("%f") reads that newline and fails. The space before %c in the format string consumes whitespace, which fixes it.
  • Negative zero printed: Converting 0 °F to Celsius gives approximately −17.78, but some edge cases like -0.0 can appear. That is harmless; you can ignore it or round with printf("%.1f").
  • Compiler warning about scanf: Some compilers warn about scanf being unsafe. For a learning program, you can ignore it or use fgets plus strtof for full control.

Frequently Asked Questions

What is the formula for Celsius to Fahrenheit in C?

The formula is F = (C × 9.0 / 5.0) + 32.0. In C code, you write fahrenheit = (celsius * 9.0 / 5.0) + 32.0;. Make sure celsius is a float or double, and use 9.0 and 5.0 instead of 9 and 5 to avoid integer division.

Why does my C program give 0 for every conversion?

That almost always means you declared your variables as int. Integer division truncates the fractional part, so (5 / 9) equals 0. Change the variable types to float or double and use floating-point literals like 5.0 and 9.0.

How do I convert Kelvin to Fahrenheit in C?

Convert Kelvin to Celsius first by subtracting 273.15, then convert that Celsius value to Fahrenheit using (C × 9.0 / 5.0) + 32.0. In code: f = ((k - 273.15) * 9.0 / 5.0) + 32.0;. There is no single-step formula you need to memorize.

Is it better to use float or double for temperature?

Either works for normal temperatures. double gives more precision and is the default in many C libraries, but float uses less memory. For a simple converter, double is a safe choice because it avoids rounding surprises and matches the %f format without extra care.

Can I write a temperature converter without scanf?

Yes. You can read command-line arguments from argv, or read a line with fgets and parse it with strtof or atof. That approach is more robust because it handles invalid input gracefully and avoids the newline-in-buffer problem.

What temperature scales can I add beyond C and F?

Kelvin is the most common addition. Rankine is another absolute scale used in some engineering fields: Rankine = Fahrenheit + 459.67. You can add any linear scale by defining two reference points and deriving the conversion formulas, but for everyday use, C, F, and K cover almost all needs.