Tuesday, July 28, 2009

What is wrong with my C++ program?

When run, the output shows both the line for A/B and not A/B why


do


{


cout %26lt;%26lt; "It is your turn to attack" %26lt;%26lt; endl


%26lt;%26lt; "Do you: " %26lt;%26lt; endl


%26lt;%26lt; "A. Attack with your " %26lt;%26lt; wname %26lt;%26lt; endl


%26lt;%26lt; "B. Cast " %26lt;%26lt; mname %26lt;%26lt; endl


%26lt;%26lt; "---%26gt; ";


cin %26gt;%26gt; Attack;





if (Attack == 'A')


{


cout %26lt;%26lt; "You hack at the monster with your " %26lt;%26lt; wname %26lt;%26lt; "." %26lt;%26lt; endl;


actualpatt = mpdef - (rand () % (pdam + 2) + (pdam - 2));


newMHP = mhp - actualpatt;


}


if (Attack == 'B')


{


cout %26lt;%26lt; "You cast " %26lt;%26lt; mname %26lt;%26lt; " on the monster." %26lt;%26lt; endl;


actualmatt = mmdef - (rand () % (mdam + 2) + (mdam - 2));


newMHP = mhp - actualmatt;


}


if (Attack != 'A' || Attack != 'B')


cout %26lt;%26lt; "That is not a valid attack. Try again!" %26lt;%26lt; endl;


} while (Attack != 'A' || Attack != 'B

What is wrong with my C++ program?
Look at the last If statement: Assuming the only inputs are 'A' and 'B', the last if will always be true. If Attack is 'A', it's not 'B', and vice-versa.





I think you want %26amp;%26amp; for that if (and the while, too) instead of ||.





Stylistically, I'd prefer:





if (Attack == 'A')


{


}


else if ( Attack =='B' )


{


}


else


{


// the error message here


}





or even





switch ( Attack )


{


case 'A':


....


break;


case 'B':


.....


break;


default:


.....


break;


}





Both instantly show that the three conditions are alternatives of each other rather than possibly sequential tests.





Hope that helps.
Reply:"When run, the output shows both the line for A/B and not A/B"





I don't understand your question. You say that it shows both, then not.





Oh ok,





this always evaluates to true "if (Attack != 'A' || Attack != 'B')"





you want





"if (Attack != 'A' %26amp;%26amp; Attack != 'B')"





same thing in your while check.


No comments:

Post a Comment