C Program to Convert Celsius to Fahrenheit
This C program aims to convert Celsius temperatures to Fahrenheit. However, some users have encountered an issue where the program incorrectly outputs 0. This article explores the reason behind this issue and provides a solution.
Problem Statement
Consider the following C 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>
When executing this code, some users experience an erroneous output of 0.
Solution
The problem lies in the calculation of the fahrenheit value. The expression (5/9) is performing integer division by default, which results in 0. To ensure floating-point division, the expression should be modified to (5.0/9). Here's the corrected code:
<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>
With this modification, the program will correctly compute and display the Fahrenheit temperature when provided with a Celsius value.
The above is the detailed content of Why Does My C Celsius to Fahrenheit Converter Output 0?. For more information, please follow other related articles on the PHP Chinese website!