Multiple options for if/elseif/else statements?

4 Ansichten (letzte 30 Tage)
Dalton Capps
Dalton Capps am 30 Okt. 2015
Beantwortet: Geoff Hayes am 31 Okt. 2015
I am making a program for a rock, paper, scissors simulator. Should I make an if statement for each possible input (rock/paper/scissors) and then each option afterwards, or instead combine them into one single if statement? Thanks for your help in advance! (Excuse my dumb comments, I want this assignment to be funny.) My code is as follows:
%rps
fprintf ('I am going to assume you know how Rock, Paper, Scissors works. Best of luck, my liege.\n')
fprintf ('(1) Rock \n')
fprintf ('(2) Paper \n')
fprintf ('(3) Scissors \n')
%ask for weapon
w=input('What weapon shall you select, sire? ');
opp=randi (3);
if w>=3.000000001;
fprintf ('"An Aggie does not lie, CHEAT, or steal." *glares at user* ')
end
if w<=0;
fprintf ('"An Aggie does not lie, CHEAT, or steal." *glares at user* ')
end
if 0<w<=.99999;
opp = 1;
fprintf ('Well would you look at that! A tie?! Aint that the darndest thing?')
else opp = 2;
fprintf ('It would appear that you have lost :( ... Paper beats rock. Better luck next time!')
else opp =3;
fprintf ('VICTORY IS OURS! Your rock crushes those scirssors! 8/8 performance!')
end

Antworten (1)

Geoff Hayes
Geoff Hayes am 31 Okt. 2015
Dalton - the first thing that you might want to do is to cast the "weapon" selected by the user and the random integer to be the same data type so that you can do an accurate comparison to see if both are identical (or the weapon selected by the user is outside of the interval [1,3]). This way you can avoid the floating-point conditions that you have coded. Something like
w = uint8(input('What weapon shall you select, sire? '));
opp = uint8(randi(3));
Since the only possible selections are 1,2, and 3, then casting as an 8-bit unsigned integer is sufficient. Now you can do a check to see if w is invalid, or is identical to opp as
if w < 1 || w > 3
fprintf ('"An Aggie does not lie, CHEAT, or steal." *glares at user* \n');
elseif w == pop
fprintf ('Well would you look at that! A tie?! Aint that the darndest thing?\n')
else
% do the rest here
end
As for what you do next, creating an if statement for each possible w or one large if statement for each possible pair of w and opp, you could do either. I might choose the first option because it is a little more tidy and makes it clear what happens if the user selects a rock, then in the body have the if/elseif with the opponent either choosing paper or scissors. And then repeating the same for if the user/liege chooses paper or scissors.

Kategorien

Mehr zu Just for fun finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by