Easy problem just can't tell whats wrong with my formula

can any body tell me why celsius always equates to 0?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//-| ---------------------------------------------------------------
//-| Assignment ID: HWK2
//-| File name:     convertTemp.cpp  
//-| Due:           Sep 19 at 5 pm
//-| Author: bfields Byron Fields
//-| Description:   This program converts Fahrenheit temperature 
//-|                into Celsius temperature. 
//-| ---------------------------------------------------------------
#include <iostream>
using namespace std;
int main()
{
cout << "(c) 2012, bfields Byron Fields." << endl;

float Fahr;
float Cels;

cout << "This program converts Fahrenheit temperature into Celsius temperature." << endl;

cout << "Please enter the temperature in Fahrenheit : " << endl;

cin >> Fahr;

Cels = (Fahr - 32) * (5/9);

cout << "The equivalent temperature in Celsius is : " << Cels << endl;

return 0;
}
I'm amazed how common this problem is.

Integer division. (5/9) since 5 and 9 are both integers, the result will be an integer.

Therefore 5/9 is zero. Which is why your result is always zero.


If you want floating point division, you have to make at least one of them a floating point. Or... do the multiplication first instead of the division:

1
2
3
Cels = (Fahr - 32) * 5 / 9;  // option 1:  get rid of parenthesis to do the multiplication first

Cels = (Fahr - 32) * (5.0f / 9.0f);  // option 2: do floating point division 
Try changing 5/9 to 5.0 / 9.0.

As it is now, I have a feeling that it is being stored as an int, and since 5/9 is less than 1, it is being counted as 0.

If you change 5 or 9 to 5.0 or 9.0 respectively, it will be stored as a float and you will get the answer you want.

Edit: that solves the problem when I run it too

Edit2: darn you Disch
Last edited on
thanks for the help you guys. rookie mistake.
Topic archived. No new replies allowed.