Home > Backend Development > C++ > Why Does My C Celsius to Fahrenheit Converter Output 0?

Why Does My C Celsius to Fahrenheit Converter Output 0?

DDD
Release: 2024-10-25 05:26:29
Original
468 people have browsed it

Why Does My C   Celsius to Fahrenheit Converter Output 0?

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template