I was using if and Elseif statements. Everytime I input the third option the print for the second option appears.
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Cameron
2023-3-13
编辑:Cameron
2023-3-13
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 个评论
Voss
2023-3-13
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!