Hey guys, I'm new to this website and was hoping to get some help.
So I'm doing this conversion program, and I'm having trouble with getting the Farhenheit to Celcius part to work. I currently enter the code before and I get for any number that Kelvin/Celsius enter 0. Any solutions?
//Basic conversion.
#include<iostream>
using namespace std;
double F=0,Cel=0,Kel=0;
void Celsius() {
Cel=( F -32)*5/9;
cout<<"The solution is Celsius is: "<<Cel<<endl;
}
int main(){
double F=0,Cel=0,Kel=0;
cout<<"What is the temperature in degress Fahrenheit?"<<endl;
cin>>F;
cout<<"You have entered:\n"<<F<<endl<<endl;
Celsius();
Kel=(F-32)*5/9+273;
cout<<"The solution in Kelvin is: "<<Kel<<endl;
cout<<"The solution is Celsius is: "<<Cel<<endl;
system("Pause");
return 0;
}
This is because you have shadowed the variables F, Cel, Kel in the main function. Basically when you ask for input you get the local F variable input to be the user input and the initialized global variables remains 0. The Celsius function then uses the global variable since the main function has not passed the variable with input to the function Celsius.
My advice, pass the variables from main as parameters to Celsius and return the result to main as a double.
#include<iostream>
usingnamespace std;
double Celsius(double Farh)
{
double Cel = (Farh -32) * 5/9;
cout << "The solution is Celsius is: "<< Cel << endl;
return Cel;
}
int main()
{
double F = 0, Cel = 0, Kel = 0;
cout << "What is the temperature in degress Fahrenheit?" << endl;
cin >> F;
cout << "You have entered:\n" << F << endl << endl;
Cel = Celsius(F);
Kel = (F-32) * 5/9 + 273;
cout << "The solution in Kelvin is: "<< Kel << endl;
cout << "The solution is Celsius is: "<< Cel << endl;
system("Pause");
return 0;
}
I would also like to mention that it is generally not a good idea to use global variables like that.
That might be because the local variables hide the global variables of the same name. You work with the local variables in main, and Celsius() operates on the global variables.
Suggestion: Get rid of the global variables. Pass the fahrenheit temperature to the Celsius function and return the Celcius temperature.