Sunday, August 2, 2009

When i run this c++ program is runs all three answers instead of just 1?

#include %26lt;iostream%26gt;





using namespace std;





int main()


{





int answer1, answer2, answer3;


int counter=0;





cout %26lt;%26lt;" Please choose two landmarks" %26lt;%26lt; endl;


cout %26lt;%26lt; " 1. Millenium Park" %26lt;%26lt; endl %26lt;%26lt; "2. Statue of Liberty" %26lt;%26lt; endl %26lt;%26lt; "3. Grand Canyon" %26lt;%26lt; endl;


cin %26gt;%26gt; answer1;


cin %26gt;%26gt; answer2;








if(answer1=='1'||answer2=='1'%26amp;%26amp;answer1==...


{


cout %26lt;%26lt; " 810 miles and a 13 hour trip" %26lt;%26lt; endl;


counter++;


}





if(answer1=='2'%26amp;%26amp;answer3=='3');


{


cout %26lt;%26lt; "1,738 miles and a 25 hour trip" %26lt;%26lt; endl;


counter++;


}





if(answer2=='2'%26amp;%26amp;answer3=='3');


{


cout %26lt;%26lt; " 2,395 miles and a 36 hour trip" %26lt;%26lt; endl;


counter++;


}





system("pause");


return 0;


}

When i run this c++ program is runs all three answers instead of just 1?
The problem is you have a semi-colon after the IF statement. That counts as a command, so the conditional stops being applied.





Your program is basically saying:


if(...) do nothing


print "whatever"


if(...) do nothing


print "whatever


etc.





So it is printing all three statements.

hydrangea

No comments:

Post a Comment