I was using if and Elseif statements. Everytime I input the third option the print for the second option appears.
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
clc
p1 = input('Player 1 Play:','s');
p2 = input('Player 2 Play:','s');
if (p1 == 'P') || (p1 == 'p') && (p2 == 'r') || (p2 == 'R')
fprintf('Player 1 wins the game because paper cover rock');
elseif (p1 == 's') || (p1 == 'S') && (p2 == 'p') || (p2 == 'P')
fprintf('Player 1 wins the game because Scissor cut paper');
elseif (p1 == 's') || (p1 == 'S') && (p2 == 'R') || (p2 == 'r')
fprintf('Player 2 wins the game because Rock break scissor');
end
Player 1 Play:
s
Player 2 Play:
r
Player 1 wins the game because Scissor cut paper
0 commentaires
Réponses (2)
Cameron
le 13 Mar 2023
Modifié(e) : Cameron
le 13 Mar 2023
The way you've written this, your program checks for this first
(p1 == 's')
so, seeing that you've selected "s" it will always defualt to that. You should use the lower() function in a case like this. That way, if the input is "S" or "s", your output will always be "s". It's easier to compare that way.
p1 = input('Player 1 Play:\n','s');
p2 = input('Player 2 Play:\n','s');
if strcmp(lower(p1),'p') && strcmp(lower(p2),'r')
fprintf('Player 1 wins the game because paper cover rock');
elseif strcmp(lower(p1),'s') && strcmp(lower(p2),'p')
fprintf('Player 1 wins the game because Scissor cut paper');
elseif strcmp(lower(p1),'s') && strcmp(lower(p2),'r')
fprintf('Player 2 wins the game because Rock break scissor');
else %after you finish writing all the rest of the elseif statements out
fprintf('Entry must be r, p, or s')
end
0 commentaires
Voss
le 13 Mar 2023
Adjust your parentheses so that the || conditions are checked together, then the &&:
if (p1 == 'P' || p1 == 'p') && (p2 == 'r' || p2 == 'R')
fprintf('Player 1 wins the game because paper cover rock');
elseif (p1 == 's' || p1 == 'S') && (p2 == 'p' || p2 == 'P')
fprintf('Player 1 wins the game because Scissor cut paper');
elseif (p1 == 's' || p1 == 'S') && (p2 == 'R' || p2 == 'r')
fprintf('Player 2 wins the game because Rock break scissor');
end
It's like the difference between these two expressions:
true || false && false || false
(true || false) && (false || false)
Note that you can use strcmpi to cut down on the number of conditions you're checking and improve code clarity. You can also check p1 and p2 at once.
p = [p1 p2];
if strcmpi(p,'pr')
elseif strcmpi(p,'sp')
elseif strcmpi(p,'sr')
end
% (what about 'rp', 'ps', 'rs', 'rr', 'pp', 'ss'?)
0 commentaires
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!