Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-10-25 05:22:29
Original
924 people have browsed it

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

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

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!

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!