Well there are 2 things I like to do (so may only be me):
1. Create and / or initialise variables at the start of functions / code
eg. In main you create your float variables inside the if statements, but you do it twice. So start of main for me would look like:
Code:
int main()
{
int temp;
float tempf, tempc;
This helps in 2 ways:
a. You don't have to search throughout my code to find variable types as they are always located in the same place.
b. Compared to yours, no need for useless second invocation of float creation.
2. I am a bit of a nazi when it comes to repetition of code. In your example this would be the replication of all the code in your if's.
Your code:
Code:
if ( temp == 1){
cout << "You chose Fahrenheit.\n ";
cout << endl;
cout << "Please type the Degrees Fahrenheit you would like convert into celsius.\n ";
cout << "\nFahrenheit: ";
float tempf, tempc;
cin >> tempf;
tempc = degreeFahrenheit(tempf);
cout << endl;
cout << tempf << " Degrees Fahrenheit is equal to " << tempc << " Degreess Celsuis. \n";
}
else if (temp == 2){
cout << "You Chose Celsius.\n ";
cout << endl;
cout << "Please type the Degrees Celsius you would like convert into Fahrenheit.\n";
cout << "\nCelsuis: ";
float tempc, tempf;
cin >> tempc;
tempf = degreeCelsuis(tempc);
cout << endl;
cout << tempc << " Degress Celsuis is equal to " << tempf << " Degrees Fahrenheit.\n";
}
else {
cout << "You typed an invalid entry. Please rerun with either option 1 or 2\n ";
}
My alternative:
Code:
float tempin, tempout;
string from, to;
bool valid = true;
if ( temp == 1)
{
from = "Fahrenheit";
to = "Celsuis";
cin >> tempin;
tempout = degreeFahrenheit(tempin);
}
else if (temp == 2)
{
from = "Fahrenheit";
to = "Celsuis";
cin >> tempin;
tempout = degreeCelsuis(tempin);
}
else
{
cout << "You typed an invalid entry. Please rerun with either option 1 or 2\n ";
valid = false;
}
if (valid)
{
cout << "You chose "<<from<<endl;
cout << endl;
cout << "Please type the Degrees "<<from<<" you would like convert into "<<to<<endl;
cout << from<<": ";
cout << endl;
cout << tempin << " Degrees "<<from<<" is equal to " << tempout << " Degreess "<<to<<endl;
}
This untested but you get the rough idea.