cppbeginner10 minutes
Fix the Bug in a Simple Temperature Converter
Debug a basic C++ function that is supposed to convert temperatures from Celsius to Fahrenheit but currently produces incorrect results.
Challenge prompt
You are given a function meant to convert temperature values from Celsius to Fahrenheit using the formula F = (C * 9/5) + 32. However, the current implementation returns incorrect values. Identify and fix the bug so the function returns the correct Fahrenheit temperature for any Celsius input.
Guidance
- • Review the arithmetic operations and their order in the formula.
- • Watch out for integer division pitfalls in C++.
- • Test the function with common values like 0°C (should return 32°F) and 100°C (should return 212°F).
Hints
- • Check if the division 9/5 is computed as integer division which may cause truncation.
- • Make sure multiplication and addition are done in the right order without losing precision.
Starter code
double celsiusToFahrenheit(int celsius) {
return celsius * 9 / 5 + 32;
}Expected output
celsiusToFahrenheit(0) should return 32 celsiusToFahrenheit(100) should return 212
Core concepts
arithmetic operationsoperator precedencedata types and integer division
Challenge a Friend
Send this duel to someone else and see if they can solve it.