#include <iostream>
float ConvertF(float);
float ConvertC(float);
int main()
{
usingnamespace std;
float TempFer;
float TempCel;
int x;
cout<<"You need to convert temp in F or C?"<<endl;
cout<<"1: F -> C"<<endl;
cout<<"2: C -> F"<<endl;
cin>>x;
if (x==1)
{
cout<<"Please enter temp in F : ";
cin>>TempFer;
cout<<endl;
TempCel=ConvertC(TempFer);
cout<<"Temp in C is "<<TempCel<<endl;
}
if (x==2)
{
cout<<"Please enter temp in C : ";
cin>>TempCel;
cout<<endl;
TempFer=ConvertF(TempCel);
cout<<"Temp in F is "<<TempFer<<endl;
}
else
{
cout<<"Invalid number."<<endl;
}
return 0;
}
float ConvertF(float TempCel)
{
float TempFer;
TempFer=((TempCel*9)/5)+32;
return TempFer;
}
float ConvertC(float TempFer)
{
float TempCel;
TempCel=((TempFer -32)*5)/9;
return TempCel;
}
By executing this strange things happen : if I select 2 it is ok, if i select an invalid option the right message comes up...but if i select option 1, the program executes the conversion but after that the Invalid number message comes up...can you tell me why?
I resolved the problem using another if statement in line 39 and it now says :
if ((x<1)||(x>2))
and things work as should, but i want to understand what i am doing wrong!!!
elseif ?? I am not familiar with this ... i tried it (obviously did somthing wrong) but it dos not compile. It takes me to line 40 and says "40 expected `(' before '{' token "
I tried this (thinkng that you invite me to do something like that):
elseif (x!=1 || x!=2)
but again same thing happens ... maybe i cannot use the else keyword?
I just want to understand how else works...
if(/*CONDITION_TO_EVALUATE*/) //First Condition To Test
{
}
elseif(/*CONDITION_TO_EVALUATE*/) //Tacks On Another Condition
{
}
elseif(/*CONDITION_TO_EVALUATE*/) //You Can Do This Over And Over
{
}
else //Default Instructions If None Of The Other Conditions Are Met
{
}
EDIT: Also in the post where you said you tried to use else if, you probably want an AND comparison instead of OR.
Hi Jack. When you choose option 1 in your original code, the computer executes the first if statement absolutely perfectly, as it should, as you said.
Then it moves down to the next if statement in line 30, which as Zhuge pointed out is completely independent of any previous code, and thinks, “Well, Jack didn’t select number 2 here, so I better print out the else statement which is connected to it, which as you know after tearing your hair out, is “Invalid number”. The computer is just doing what you have inadvertently told it to do.
The solution, as Zhuge and Computergeek01 have said, is to allow only one possible outcome in cases like this, by tying all possibilities tightly together with if, else if, else if (as many times as you like) with a final else statement.
I find it useful to think of if /else statements as if/or else, as our mothers used to say!
Eg
if (you do your homework)
{You can go to the movies}
else
{You are grounded all weekend!}