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

Why Does My Fahrenheit to Celsius Conversion Program Output 0?

Susan Sarandon
Release: 2024-10-25 02:47:02
Original
285 people have browsed it

Why Does My Fahrenheit to Celsius Conversion Program Output 0?

Why Does This C Program Convert Fahrenheit to Celsius Incorrectly?

A C program that attempts to convert Fahrenheit temperatures to Celsius is causing confusion due to an incorrect output of 0. Let's delve into the code and explain the issue.

The program begins by including the necessary standard input and output library and defines some variables.

<code class="cpp">#include <iostream>
using namespace std;

float celsius;
float fahrenheit;</code>
Copy after login

The code then prompts the user to input a Celsius temperature and stores it in the celsius variable.

<code class="cpp">cout << "Enter Celsius temperature: ";
cin >> celsius;</code>
Copy after login

The computation for converting Celsius to Fahrenheit is as follows:

<code class="cpp">fahrenheit = (5/9) * (celsius + 32);</code>
Copy after login

The issue arises here. The expression (5/9) performs integer division by default, resulting in 0. To obtain the correct fractional result, we need to cast one of the operands to a floating-point type.

<code class="cpp">fahrenheit = (5.0/9) * (celsius + 32);</code>
Copy after login

By using floating-point division, we ensure the computation is done correctly and the fractional part is preserved.

The program concludes by outputting the Fahrenheit temperature.

<code class="cpp">cout << "Fahrenheit = " << fahrenheit << endl;</code>
Copy after login

By making this correction, the program will now correctly convert and display Fahrenheit temperatures based on user-provided Celsius values.

The above is the detailed content of Why Does My Fahrenheit to Celsius Conversion Program 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