Home  >  Article  >  Backend Development  >  Why Does My C Celsius to Fahrenheit Conversion Always Output 0?

Why Does My C Celsius to Fahrenheit Conversion Always Output 0?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 05:22:29925browse

Why Does My C   Celsius to Fahrenheit Conversion Always Output 0?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn