Incorrect Conversion from Celsius to Fahrenheit
In C , converting from Celsius to Fahrenheit using floating-point arithmetic requires special attention. Consider the following code:
<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>
Why does this program output 0 for any Celsius input?
The issue lies in the integer division of (5/9). By default, C performs integer division, which results in 0 in this case. To address this, we must cast one of the operands to a floating-point type to force floating-point division. The corrected code below:
<code class="cpp">#include <iostream> using namespace std; int main() { float celsius; float fahrenheit; cout << "Enter Celsius temperature: "; cin >> celsius; fahrenheit = (5.0/9) * (celsius + 32); cout << "Fahrenheit = " << fahrenheit << endl; return 0; }</code>
The above is the detailed content of Why Does My C Celsius to Fahrenheit Conversion Always Output 0?. For more information, please follow other related articles on the PHP Chinese website!