- The Celsius-to-Fahrenheit formula: F = C × 9/5 + 32
- Why
doubleis essential — temperatures are almost always fractional - The classic integer-division bug:
9 / 5gives 1, not 1.8 - How to avoid it: use
9.0and5.0, or cast one operand - How to format the output with one decimal place, matching common weather reports
- The reverse conversion (Fahrenheit → Celsius) and how to add it to the program
The Celsius → Fahrenheit formula
The Celsius and Fahrenheit scales both measure temperature, but they use different zero points and different sizes for one degree. Celsius (formerly Centigrade) puts the freezing point of water at 0° and the boiling point at 100°. Fahrenheit puts the same points at 32° and 212° — a span of 180 degrees.
To convert from Celsius to Fahrenheit, use the linear formula:
F = C × 9/5 + 32
The 9/5 factor accounts for the different sizes of the two scales — one degree Celsius is 1.8 times as large as one degree Fahrenheit. The + 32 shift accounts for the different zero points. Check: 0 °C → 0 × 1.8 + 32 = 32 °F (water freezes). 100 °C → 100 × 1.8 + 32 = 212 °F (water boils). The formula works.
This is a classic C exercise because it has a subtle trap: if you write C * 9 / 5 with C as an integer, the compiler does integer division 9 / 5 = 1, not 1.8. So 100 °C would give 100 * 1 + 32 = 132 instead of 212 — very wrong, with no warning from the compiler (unless you compile with -Wconversion). The fix is to use floating-point arithmetic throughout — either double variables or 9.0 / 5.0 literals.
💡 In one line: F = C * 9.0 / 5.0 + 32.0. The .0 suffixes force floating-point arithmetic. Without them, 9 / 5 truncates to 1 and the answer is wrong by a factor of 1.8.
The -40 coincidence is worth noting: -40 °C = -40 °F. That's the only temperature where the two scales agree. If you run the program with -40, you should get -40.00 in both scales. It's a nice sanity check.
Choosing the right data types
"Proper data types" in the assignment title is the key phrase. Here's the reasoning:
| Type | Works? | Why or why not |
|---|---|---|
int | No | Temperatures are fractional (e.g., 36.6 °C). int truncates. |
float | Yes | 7 significant digits — enough for temperatures. But double is the default for floating-point literals in C. |
double | Best choice | 15 significant digits — far more than needed, but standard and safe. No cost on modern hardware. |
long double | Overkill | Temperatures don't need 18+ significant digits. Use double; keep it simple. |
For this program, use double for both celsius and fahrenheit. That's the "proper data type" the assignment is asking about. The formula's 9/5 factor becomes 9.0 / 5.0, which is 1.8 — the floating-point ratio. No truncation, no surprises.
Why 9.0 and 5.0 specifically, not 9 and 5? Because even if celsius is a double, writing celsius * 9 / 5 would evaluate 9 / 5 first (integer division = 1) before multiplying by celsius. Wait, no — C evaluates left to right with the same precedence, so celsius * 9 happens first (giving a double), then / 5 divides by 5 (yielding 1.8). So celsius * 9 / 5 actually works when celsius is double. But it's fragile — if someone later changes celsius to int, the same line breaks. Writing 9.0 / 5.0 makes the intent explicit and is robust against future type changes.
Actually, let's be careful. In celsius * 9 / 5, the order of operations is: (celsius * 9) / 5 because * and / have the same precedence and associate left to right. So celsius * 9 is computed first. If celsius is a double, celsius * 9 is a double (9 is promoted to double), and dividing by 5 (also promoted to double) gives the correct result. So celsius * 9 / 5 works when celsius is double.
But if celsius is an int, then celsius * 9 is int, and dividing by 5 is integer division — truncation. So celsius * 9 / 5 with celsius = 37 gives 37 * 9 = 333, then 333 / 5 = 66 (truncating 66.6 to 66). Then + 32 = 98, instead of the correct 98.6.
The lesson: use double throughout, or use 9.0 / 5.0. Both work. Using double variables is cleaner for a program that's entirely about temperatures. Using 9.0 / 5.0 is a defensive measure that works even with int inputs. The best code does both.
🎯 Key idea: use double for temperature — it's the "proper" type because temperatures are fractional. Write the formula as celsius * 9.0 / 5.0 + 32.0. The .0 suffixes prevent integer division even if someone later changes the variable types.
Complete C Program
Program: Celsius to Fahrenheit with proper types
#include <stdio.h>
int main(void) {
double celsius, fahrenheit;
/* Read the Celsius temperature */
printf("Enter temperature in Celsius: ");
scanf("%lf", &celsius);
/* Apply the formula: F = C * 9/5 + 32
* 9.0 and 5.0 force floating-point arithmetic — no integer division. */
fahrenheit = celsius * 9.0 / 5.0 + 32.0;
/* Print both values for reference */
printf("%.2lf degrees Celsius = %.2lf degrees Fahrenheit\n",
celsius, fahrenheit);
return 0;
}
The program is short and direct. Read the Celsius value, apply the formula, print both values for reference. The %.2lf format prints two decimal places, which is a common convention for temperature (e.g., "36.60 degrees Celsius"). For a weather-app feel, one decimal place (%.1lf) might be more natural — use whichever fits the context.
And here's a bidirectional converter — Celsius to Fahrenheit and back — that demonstrates the round-trip:
Variant: round-trip conversion
#include <stdio.h>
int main(void) {
double celsius, fahrenheit, celsius_back;
printf("Enter temperature in Celsius: ");
scanf("%lf", &celsius);
/* Celsius → Fahrenheit */
fahrenheit = celsius * 9.0 / 5.0 + 32.0;
/* Fahrenheit → Celsius (reverse formula) */
celsius_back = (fahrenheit - 32.0) * 5.0 / 9.0;
printf("\nInput: %.2lf °C\n", celsius);
printf("Converted: %.2lf °F\n", fahrenheit);
printf("Round-trip: %.2lf °C\n", celsius_back);
return 0;
}
The reverse formula is F → C: C = (F − 32) × 5/9. Substituting F from the first conversion, the round-trip should give back the original Celsius — a good check that both formulas are correct. Due to floating-point rounding, the round-trip may differ in the last digit or two (e.g., 36.6 → 97.88 → 36.60), but should match within a few parts in 1015. If the round-trip is wildly off, something is wrong.
Program Output
Here is typical output for 37 °C (normal body temperature):
Enter temperature in Celsius: 37
37.00 degrees Celsius = 98.60 degrees Fahrenheit
Check: 37 × 9/5 + 32 = 66.6 + 32 = 98.6 °F. Correct. The fractional result (98.6) is exactly what double preserves — an int version would have produced 98, losing the .6.
For 0 °C (freezing point):
Enter temperature in Celsius: 0
0.00 degrees Celsius = 32.00 degrees Fahrenheit
Check: 0 × 1.8 + 32 = 32 °F. Correct.
For 100 °C (boiling point):
Enter temperature in Celsius: 100
100.00 degrees Celsius = 212.00 degrees Fahrenheit
Check: 100 × 1.8 + 32 = 212 °F. Correct.
For -40 °C (the famous intersection):
Enter temperature in Celsius: -40
-40.00 degrees Celsius = -40.00 degrees Fahrenheit
Both readings are -40 — the scales agree at this temperature. Check: -40 × 1.8 + 32 = -72 + 32 = -40. Correct.
For a fractional input like 36.6:
Enter temperature in Celsius: 36.6
36.60 degrees Celsius = 97.88 degrees Fahrenheit
Check: 36.6 × 1.8 + 32 = 65.88 + 32 = 97.88 °F. Correct. This is another input that int couldn't handle — int would have read 36 and given 96.80 °F instead.
And the round-trip variant:
Enter temperature in Celsius: 37
Input: 37.00 °C
Converted: 98.60 °F
Round-trip: 37.00 °C
The round-trip returns exactly 37.00 — both formulas are correct inverses of each other. Floating-point rounding happens to work out exactly here; other inputs might show 36.99 or 37.01 due to tiny rounding errors, but within a few parts in 1015.
🔍 Try this: modify the program to use int for celsius and leave the formula as celsius * 9 / 5 + 32. Compile with gcc -Wall. You'll see a warning about integer division. Run with input 37 — you get 98, not 98.60. That's the classic integer-division bug in action. Fix it by using 9.0 / 5.0, and the correct result returns.
Step-by-Step Explanation
Let's walk through the program, then examine the formula and the integer-division trap in detail.
1. Declaring the variables
double celsius, fahrenheit; — declares two double variables. Each occupies 8 bytes on typical systems and holds about 15 significant decimal digits, which is far more precision than any temperature measurement could ever use. But double is the right choice anyway because it's the default floating-point type in C, and using it avoids the integer-division trap entirely.
2. Reading the Celsius value
printf("Enter temperature in Celsius: "); — the prompt. The trailing space (no \n) means the user types on the same line as the prompt, which is standard for interactive input.
scanf("%lf", &celsius); — reads a double into celsius. The %lf specifier matches double; the & passes the address so scanf can write into the variable. If the user types "37", celsius becomes 37.0. If they type "36.6", it becomes 36.6.
3. The conversion formula
fahrenheit = celsius * 9.0 / 5.0 + 32.0; — the heart of the program. Evaluate left to right, respecting precedence:
celsius * 9.0— multiply Celsius by 9.0. Sincecelsiusisdoubleand 9.0 isdouble, the result isdouble. For 37, this gives 333.0./ 5.0— divide by 5.0. The result isdouble. For 333.0, this gives 66.6.+ 32.0— add 32.0. For 66.6, this gives 98.6.
The final result 98.6 is stored in fahrenheit. The .0 suffixes on 9.0, 5.0, and 32.0 are stylistic — they make it clear these are floating-point constants, and they protect against accidental integer division if someone later changes the types. Even if celsius were an int, celsius * 9.0 would be a double (int promoted to double), and the rest of the expression would also be double — so the formula would still work. That's the value of the suffixes.
4. The integer-division trap
What if you wrote celsius * 9 / 5 + 32 (without the .0)? If celsius is double, the result is still correct, because celsius * 9 promotes 9 to double, and dividing by 5 promotes 5 to double. But if celsius is int, the picture changes dramatically.
With int celsius = 37;:
celsius * 9= 37 × 9 = 333 (int)333 / 5= 66 (int division — truncates 66.6 to 66)66 + 32= 98 (int)
The correct answer is 98.6, but the integer version gives 98. An error of 0.6 °F, small in absolute terms but wrong nonetheless — and it would compound in a real program that uses the result for further calculations.
The fix is to use 9.0 / 5.0 instead of 9 / 5. With the .0 suffixes, the ratio is 1.8 (a double), and even if celsius is int, the multiplication and division proceed in double precision. The result is correct.
Alternatively, cast one operand: celsius * (9.0 / 5.0) + 32 — the parenthesized 9.0/5.0 is computed once as 1.8, then multiplied by Celsius. Or: (double)celsius * 9 / 5 + 32 — the cast promotes celsius to double, then the rest proceeds in double. All three approaches work; the .0 suffixes are the simplest.
5. Printing the result
printf("%.2lf degrees Celsius = %.2lf degrees Fahrenheit\n", celsius, fahrenheit); — prints both values with two decimal places. Using a single printf with two specifiers is cleaner than two separate calls — it puts both values on one line, separated by " = ". The \n at the end ensures the next output (or the shell prompt) appears on a new line.
The %.2lf specifier: % starts the format, lf is the type (double), and .2 is the precision (two decimal places). So 37.0 prints as "37.00" and 98.6 prints as "98.60". Without the .2, the default is six decimal places (e.g., "37.000000"), which is noisy. Two decimal places matches common weather reports — "25.30 degrees" — and is precise enough for any practical use.
6. The reverse formula
The round-trip variant introduces the reverse formula: celsius_back = (fahrenheit - 32.0) * 5.0 / 9.0;. This undoes the Celsius → Fahrenheit transformation, going back to Celsius. The parentheses matter: fahrenheit - 32.0 first, then multiply by 5.0, then divide by 9.0. Without the parentheses, fahrenheit - 32.0 * 5.0 / 9.0 would compute 32 * 5 / 9 = 160/9 ≈ 17.78 first (due to multiplication having higher precedence than subtraction), then subtract that from fahrenheit — a completely different (and wrong) calculation.
The reverse formula demonstrates that the conversion is invertible. Converting C → F and then F → C should give back the original C, up to floating-point rounding. If the round-trip is off by more than a rounding error, something is wrong.
7. Why "proper data types" matters
The assignment title specifically says "using proper data types." The "proper" type for a temperature is a floating-point type, because:
- Temperatures are routinely measured to one or two decimal places (36.6 °C, 98.6 °F).
- The conversion factor 9/5 = 1.8 is fractional, so most conversions produce a fractional result even if the input is a whole number.
- The
+ 32shift is a whole number but doesn't change the fractional nature of the result. - Any real-world temperature calculation (weather forecasting, engineering, cooking) requires at least one decimal digit.
An int can only represent whole-number temperatures. For 37.5 °C, it would store 37 and give a correspondingly wrong conversion. So int is the wrong type. float would work, but double is the standard choice — it's the default floating-point type, has more precision, and costs nothing on modern hardware.
8. The -40 coincidence
Celsius and Fahrenheit agree at -40. That is, -40 °C = -40 °F. This is because the formula F = 1.8C + 32 has the solution C = F = -40: -40 = 1.8 × (-40) + 32 = -72 + 32 = -40. The two lines intersect at (-40, -40) on a graph. It's a nice sanity check for the formula — if -40 inputs to Celsius and you get -40 °F, the formula is correct. If you get something else, look for a bug.
Similarly, you can check 0 °C → 32 °F (water freezing) and 100 °C → 212 °F (water boiling). If all three of these match, the conversion is almost certainly correct.
9. Floating-point precision
double can represent about 15 significant decimal digits precisely. For temperatures, this is vastly more than needed — you don't care about the 13th decimal place of a temperature. But the extra precision means that small rounding errors in intermediate calculations (e.g., 37 × 9.0 / 5.0 is not exactly representable) don't affect the final result when rounded to two decimal places.
In particular, the intermediate value 66.6 is not exactly representable in binary floating-point — it's actually 66.599999999999994... The + 32.0 then gives 98.599999999999994... When printed with %.2lf, this rounds to "98.60", which is what we expect. The rounding error is invisible at the printed precision.
10. Extending the program
The natural extension is to make it a bidirectional converter — accept a letter indicating the scale ('C' or 'F') and convert accordingly. Or to print a table of conversions for a range of temperatures (e.g., from -40 to 100 in steps of 10). The table version is a great exercise in loops: for (int c = -40; c <= 100; c += 10) { ... }. That's the assignment for a later chapter (loops), but it's a natural next step once you've mastered this one.
🎯 Key idea: the Celsius → Fahrenheit formula is simple, but the integer-division trap is a classic source of bugs. Always use double for temperatures (they're fractional), and write 9.0 / 5.0 with explicit .0 suffixes — even when the variables are double, the suffixes document the intent and protect against future changes.
Frequently Asked Questions
1. Why does celsius * 9 / 5 give the wrong answer?
If celsius is an int, then celsius * 9 is an int (no rounding yet), and dividing by 5 is integer division. For celsius = 37, 37 * 9 = 333, 333 / 5 = 66 (truncating 66.6 to 66). The .6 is lost, and the final answer is 98 instead of 98.6. If celsius is a double, the same expression is correct (because celsius * 9 promotes 9 to double, then dividing by 5 gives a double), but writing it with .0 suffixes is safer and clearer.
2. What's the difference between float and double for this program?
Both work for temperature conversion. float has about 7 significant decimal digits of precision; double has about 15. For temperature, 7 digits is far more than needed (no thermometer measures to 7 digits). The practical difference is that double is the default for floating-point literals in C — writing 9.0 gives a double, not a float. So using double variables avoids any implicit conversions, and it's the standard choice. On modern hardware, double is as fast as float for scalar arithmetic.
3. What if I write 32 instead of 32.0?
In the expression celsius * 9.0 / 5.0 + 32, the 32 is an int literal. When added to a double result, it's implicitly promoted to double (32.0). So the result is the same. The .0 on 32 is stylistic — it makes the intent clear and avoids any surprise if the expression is ever restructured. Some compilers with -Wconversion might warn about the implicit conversion; the .0 avoids that. Best practice: use .0 on all floating-point literals in a floating-point expression.
4. What is the reverse formula, F → C?
The reverse is C = (F − 32) × 5/9. Start with the F value, subtract 32 (undoing the shift), then multiply by 5/9 (undoing the scale change). In C: celsius = (fahrenheit - 32.0) * 5.0 / 9.0;. This is the mathematical inverse of the forward formula. Applying both — C → F → C — should give back the original C, up to floating-point rounding.
5. What does the -40 coincidence mean?
-40 °C = -40 °F. The two scales agree at this temperature. It's the unique solution to x = 1.8x + 32, which simplifies to 0 = 0.8x + 32, so x = -40. Below -40, Celsius reads higher than Fahrenheit (e.g., -50 °C = -58 °F); above -40, Fahrenheit reads higher (e.g., 0 °C = 32 °F). The -40 point is a nice sanity check for the conversion formula.
6. Why not use long double?
long double gives even more precision than double (typically 80-bit extended precision on x86, or 128-bit quad precision on ARM), but no temperature measurement needs it. double's 15 significant digits are far more than any thermometer can resolve. Using long double is overkill and, on some platforms, slower. For temperature, double is the right balance of precision, speed, and portability.
💡 Tip: once this works, try converting Kelvin too. The formula is K = C + 273.15. Add a third variable and a third printf. Then try converting to other scales — Rankine (R = F + 459.67), Réaumur (Ré = C × 4/5). Each is a linear transformation, and writing them out gives you practice with formulas and floating-point arithmetic. You could even accept a letter ('C', 'F', 'K') and choose the conversion accordingly — that's a natural next exercise with conditional statements.