I was using if and Elseif statements. Everytime I input the third option the print for the second option appears.

1 Ansicht (letzte 30 Tage)
clc
p1 = input('Player 1 Play:','s');
Unable to run the 'fevalJSON' function because it calls the 'input' function, which is not supported for this product offering.
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

Antworten (2)

Cameron
Cameron am 13 Mär. 2023
Bearbeitet: Cameron am 13 Mär. 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

Voss
Voss am 13 Mär. 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
ans = logical
1
(true || false) && (false || false)
ans = logical
0
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'?)

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