user3371750
user3371750

Reputation:

C++ Simple Farenheit Conversion

I am trying to create a simple program that takes a value Celsius entered by the user, and converts it to Fahrenheit.

#include <iostream>

using namespace std;

int main()
{
    float celsius, farenheit;
    cout << "Enter a temperature in farenheit ";
    cin >> farenheit;
    celsius = (farenheit - 32) *  (5 / 9);
    cout << celsius;
    return 0;
}

It always prints a value of 0, why is this?

Upvotes: 1

Views: 78

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

This is because you multiply by 5 / 9, which is zero due to integer division.

If you change parentheses like this

celsius = ((farenheit - 32) *  5) / 9;

you would get the correct result.

Since you parenthesized (5 / 9), the compiler computed that value before performing multiplication. Since (5 / 9) is an integer expression, the compiler performs an integer division, meaning that the fractional part is discarded. As the result, all proper fractions become zeros.

Another way to fix this problem is to force C++ to use floating point division by making one or both numbers a floating point constant (specifically, a constant of type double) by appending .0 to them, for example:

celsius = (farenheit - 32) *  (5.0 / 9);

Upvotes: 4

Related Questions