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!