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;
}
#include <iostream>
#include <cstdlib>
usingnamespace 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.
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).
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 =]
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.