필터 지우기
필터 지우기

My while loop will not stop even when it no longer meets the requirements, how do I fix this?

조회 수: 10 (최근 30일)
I am coding a hangman, im using a while loop in here. The code for that is:
while ~(guessesLeft <= 0) || ~(correctCount == length(guessingWord-1))
incorrectCount1=0;
currentNum=0;
NewGuess=input('Please enter your guess: ','s');
for i=1:length(Guess)
if NewGuess==guessingWord(i)
Guess(i)=NewGuess;
lettersLeft=lettersLeft-1;
currentNum=currentNum+1;
correctCount=correctCount+1;
else
incorrectCount1=incorrectCount1+1;
end
end
if currentNum==0
fprintf('Your letter is not in the word!\n');
guessesLeft=guessesLeft-1;
else
fprintf('You have made a correct guess!\n');
end
disp(Guess);
end
  댓글 수: 2
Matthew Smyth
Matthew Smyth 2022년 4월 19일
Hi I managed to figure out both conditions work on their own, but the first condition does not work when the || or symbol is there, is there an issue here?

댓글을 달려면 로그인하십시오.

채택된 답변

Geoff Hayes
Geoff Hayes 2022년 4월 19일
@Matthew Smyth - look closer at your while loop condition
while ~(guessesLeft <= 0) || ~(correctCount == length(guessingWord-1))
The loop will continue so long as the user still has guesses left OR hasn't selected the correct letters. I think that this should be an AND else you will have the problem where the user has used up all of their guesses but the other condition is still true. Also, it isn't clear (to me) why you are comparing the correct count with the length of the guessing word less one character. I think that the conditions should be more like
while guessesLeft > 0 && correctCount != length(guessingWord)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by