Home > Article > Backend Development > Why Does My C Fahrenheit to Celsius Conversion Program Always Output 0?
A C program designed to convert Fahrenheit to Celsius encounters an unexpected output of zero. Here's the code along with the issue:
<code class="cpp">#include <iostream> using namespace std; int main() { float celsius; float fahrenheit; cout << "Enter Celsius temperature: "; cin >> celsius; fahrenheit = (5/9) * (celsius + 32); cout << "Fahrenheit = " << fahrenheit << endl; return 0; }</code>
Upon execution, the program doesn't accurately convert Celsius to Fahrenheit and always outputs 0.
The problem lies within the formula used to calculate Fahrenheit: fahrenheit = (5/9) * (celsius 32).
In this expression:
Therefore, 5/9 evaluates to 0, and the resulting Fahrenheit temperature is also 0, regardless of the input Celsius value.
To resolve the issue, one needs to ensure that the division operation results in a floating-point number. This can be achieved by converting one of the operands to a floating-point type. The corrected code:
<code class="cpp">fahrenheit = (5.0/9) * (celsius + 32);</code>
With this modification, 5.0/9 becomes a floating-point division, preserving the fractional part and yielding the correct Fahrenheit conversion.
The above is the detailed content of Why Does My C Fahrenheit to Celsius Conversion Program Always Output 0?. For more information, please follow other related articles on the PHP Chinese website!