So this program will convert a temperature to either celcius or fahrenheit depending on if the user type a c or f. Works fine if i type c and a number but when i type f and a number i keep getting zero. Not sure why.I think the problem is somewhere in *float celcius (float)* but cant find it. I feel like its a simple mistake but i cant see it. :/ Thanks guys!
//****************************************************************************
// This program will convert a temperature to either celcius or fahrenheit
// depending on if the user type a c or f.
//****************************************************************************
#include <iostream>
usingnamespace std;
float fahrenheit(float); // function prototype for fahrenheit
float celsius(float); // function prototype for celcius
int main()
{
float temperature;
char choice;
cout<< "Enter an F or a C and a number to be converted: ";
cin>> choice >> temperature;
if (choice=='f' || choice=='F') // If they choose F
{
cout<< temperature << " degrees in Fahrenheit in Celcius is: " << celsius(temperature) << endl;
}
elseif (choice=='c' || choice=='C') // If they choose C
{
cout<< temperature << " degrees in Celcius in Fahrenheit is: " << fahrenheit(temperature) << endl;
}
else
cout<< "You have entered an invalid letter or you have entered them in the wrong order."<< endl; // If they make a mistake
system ("pause");
return 0;
}
//**********************************************************************************************************************************
//**********************************************************************************************************************************
float fahrenheit (float temp)
{
return ((9/5*temp)+(32));
}
//**********************************************************************************************************************************
//**********************************************************************************************************************************
float celsius (float temp)
{
return ((temp-32)*(5/9));
}
It's because he's doing integer division. Any integer divided by another integer will always result in an integer. Digits after the decimal are truncated. That means 5/9 is equal to zero. Solve it by casting at least one of the numbers as a float.