Program generates random number. User has to guess it from 3 times.

조회 수: 8 (최근 30일)
Ryan
Ryan 2013년 12월 21일
댓글: Ryan 2013년 12월 22일
I've written a matlab program that generates a random integer between 1 and 10 and the user has to guess it. The user has 3 shots at guessing the number. The program worked but I tried modifying it so it shows the number of guesses that the user has left. Line 11 gives me an error I have no ideea why. I have attached the program here is the code from it:
% program generates a random number between 1 and 10
% user has to guess it from 3 tries
nr = randi([1,10]);
i = 0;
choice = input('Guess the number(you have 3 shots): ');
while choice ~= nr
i = i+1;
if i<3
% choice = input('You have %d more tries! ', i);
else
fprintf ('You blew it! The number was %d\n', nr)
break
end
end
if choice == nr
fprintf('Congratulations, you guessed the number %d!\n', nr)
end
  댓글 수: 1
John D'Errico
John D'Errico 2013년 12월 21일
It looks to be time to read the help for input. What does it expect the second argument to be?

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

채택된 답변

Walter Roberson
Walter Roberson 2013년 12월 21일
choice = input(sprintf('You have %d more tries! ', i));
  댓글 수: 1
Ryan
Ryan 2013년 12월 22일
Thank you but now I have another problem it shows from 3 to 1. So if the user guesses wrong the program returns 'You have 1 more tries' then if user guesses wrong again the program says 'You have 2 more tries'. It's basically the way around. Any ideea how could I fix this?

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

추가 답변 (1개)

Suneesh
Suneesh 2013년 12월 21일
1. When the person guess the correct number, in the ELSE part you do not do anything about the variable 'i'. Due to this the answer is guess right and the WHILE loop runs infinitely. Ideally you should get out of the loop when the answer is guess correctly.
2. Also, the user gets 4 chances to guess not 3. Once chance on line number 3 and three more chances in the loop
  댓글 수: 2
Ryan
Ryan 2013년 12월 22일
Thank you for your answer. Correct me if I'm wrong but the if from the loop is: if i<3 not i<=3 and i starts from 0 so wouldn't it be 3 chances(i=0, i=1 and i=2)? It works for me just fine with 3 chances.
Walter Roberson
Walter Roberson 2013년 12월 22일
sprintf("You have %d more tries",i) is going to be giving the wrong output if you have i counting upwards. "You have 1 more tries" should only be before "You have 2 more tries" in the case of very large values of "1".

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by