Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-10-25 03:57:30
Original
624 people have browsed it

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

C Program Encounters Unexpected Conversion Result: Fahrenheit to Celsius Discrepancy

A C program designed to convert Fahrenheit to Celsius encounters an unexpected output of zero. Here's the code along with the issue:

Code Snippet:

<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>
Copy after login

Issue Summary:

Upon execution, the program doesn't accurately convert Celsius to Fahrenheit and always outputs 0.

Problem Analysis:

The problem lies within the formula used to calculate Fahrenheit: fahrenheit = (5/9) * (celsius 32).

In this expression:

  • 5/9 is computed as an integer division. In C , if both operands in a division operation are integers, the result is also an integer.
  • Integer division truncates the result, which means any fractional part is discarded.

Therefore, 5/9 evaluates to 0, and the resulting Fahrenheit temperature is also 0, regardless of the input Celsius value.

Solution:

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!