Here is my first program, I had to use a lot of if/ else statements. For some reason the last "else" (bolded) is giving me an error and not letting me run the program. whats going on?
#include <iostream>
usingnamespace std;
constfloat MILES_PER_KM = 1.0 / 1.61;
constfloat KM_PER_MILE = 1.61;
constfloat FREEZING_F = 32.0;
constfloat FAHR_PER_CELSIUS = 9.0 / 5.0;
constfloat CELSIUS_PER_FAHR = 5.0 / 9.0;
constfloat MAX_F_TEMP = 100.0;
constfloat MIN_F_TEMP = 0.0;
int main ()
{
char unit;
float value;
cout << "Input a type and an amount (K, M, F, C): ";
cin >> unit;
cin >> value;
if (unit == 'K')
if ( value < 0 )
cout << "UNABLE TO PROCESS: Negative distances are not supported.";
else
cout << "Distance " << value << " kilometers" << " is "
<< ( value * MILES_PER_KM ) << " miles.";
elseif (unit == 'M')
if ( value < 0 )
cout << "UNABLE TO PROCESS: Negative distances are not supported.";
else
cout << "Distance " << value << " miles" << " is "
<< value * KM_PER_MILE << " kilometers.";
elseif (unit == 'C')
cout << "Temperature " << value << " C is "
<< ( (value * FAHR_PER_CELSIUS) + FREEZING_F ) << " F.";
elseif (unit == 'F')
if (value > MAX_F_TEMP || value < MIN_F_TEMP)
cout << "UNABLE TO PROCESS: Temperature too hot or too cold.";
cout << "Please enter a temperature comfortable when wearing a sweater.";
else
cout << "Temperature " << value << " F is "
<< ((value - FREEZING_F) / FAHR_PER_CELSIUS) << " C.";
else
cout << "UNABLE TO PROCESS: " << unit << " is not a recognized measurement.";
return 0;
}
and yes, the if else's are indented properly, because there are no errors for the first 3 unit types, only for the last one ( 'F' ), and i have them all exactly in the same format.
To improve your program a bit, make use of the following:
A ShowMenu function, which prints out the options with descriptions.
A switch statement that has a case for each option in the menu, possibly calling a function for each one. the switch also has a default: clause that catches bad input.
Enclose the whole thing in a loop like this:
1 2 3 4 5 6 7 8
bool Quit = false;
while (!Quit) {
//switch statement here
//user wants to quit
Quit = true;
}
If you want to use multiple statements within an if statement, you need to use braces.
In fact, I'd go further: as a matter of good practice, you should always put braces around the code that is executed conditionally, even if it is only a single statement. It is frighteningly easy to introduce bugs by going back and adding a second statement, and forgetting to add the braces. I've seen this happen in every single one of the jobs I've worked at, and I've done it a few times myself.
It's much safer to protect yourself from this by putting in the braces every time.