why isnt this working?

I seem to get this problem sometimes when working with variables,
im creating a program to translate Fahrenheit to centigrade and the only value that returns is 0..
here is my code:
#include<iostream>





int main()
{
float f;
float f2;

cout<<"Please enter the temperature in farenheit: "<<endl;
cin>>f;
f2=5/9*(f-32);

cout<<"Your temerature in centigrade is "<<f2<<"."<<endl;




system ("pause"); // execute M$-DOS' pause command
return 0;
}



any help is appreciated =]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
float f;
float f2;

cout<<"Please enter the temperature in farenheit: "<<endl;
cin>>f;
f2=5.0/9.0 * (f-32);

cout<<"Your temerature in centigrade is "<<f2<<"."<<endl;

system ("pause"); // execute M$-DOS' pause command
return 0;
}

The compiler casts the 5/9 calculation as an integer.
Last edited on
Five divided by nine is zero, so here:
f2=5/9*(f-32);
you are multiplying by zero, so the answer is zero.

If you don't want five divided by nine to come out as zero, don't use int values.
Please use [code]int i=5; // code [/code] tags when posting code.

The problem is in the line f2=5/9*(f-32);
What basically happens is that 5/9 equals 0, because both 5 and 9 are considered to be integers.
You fix this by explicitly making at least one of them a floating point value, like this: 5.0f.
In the end you'll have f2 = 5.0f / 9 * (f-32);
(You add the f at the end because you want a float, if you don't add the f you'll have a double).

Edit: I need to learn to post faster.
Last edited on
NIiiiiinnnnnnNNnn..... JARRRRRRRRRRRRRR!
well I tried the 5.0f trick and it worked =] I didn't know i had to explicitly declare that since I made f2 a float. So then is there a way that i can specify for everything in that value of f2 to be floating point, like at the beginning of the statement or something?
thanks =]
There is not. The compiler will interpret 5 as an int, and 9 as an int. You'll just have to specify what kind of values they are.
You needn't become paranoid about constants.
You just have to keep in mind that the compiler is dumb enough to require you to specify the type of the constants if you put them in an operation, like you did, otherwise it will do the default integer math.
Last edited on
hmm, okay. well thanks for the info=] that's gonna make things so much easier now.
Topic archived. No new replies allowed.