필터 지우기
필터 지우기

Matlab Count to 10 game

조회 수: 1 (최근 30일)
EaglesFan
EaglesFan 2015년 11월 9일
답변: Image Analyst 2015년 11월 9일
Hello, I'm currently working on this exercise and I don't know how to continue. Here is the exercise: In this exercise you are required to implement a simple two player counting game. The game starts by setting the count to 0. The two players should take alternative turns selecting between the numbers 1 and 2. In each turn the number the current player selects gets added to the count. The player who reaches a value 10 or larger wins the game. The program should check for input correctness. The image below has a sample run.
I currently have this:
clear
clc
sum=0;
player=1;
while (sum<10);
count=input('Enter 1 or 2: ');
fprintf('Player %d',player);
if (count==1|count==2)
sum=sum+count;
else
disp('Incorrect Input');
end
end
I know I'm quite far from solving the problem and help would be appreciated.
  댓글 수: 1
Walter Roberson
Walter Roberson 2015년 11월 9일
Do not name a variable "sum" as that interferes with using the important MATLAB routine named "sum".

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

답변 (1개)

Image Analyst
Image Analyst 2015년 11월 9일
You can check for correctness by making sure it's correct in the first place. Use questdlg to give them a choice of only 1 or 2:
clear
clc
theSum=0;
player=1;
while (theSum < 10);
promptMessage = sprintf('The sum so far = %d\nPlayer #%d\nDo you want 1 or 2?', theSum, player);
titleBarCaption = 'Continue?';
button = questdlg(promptMessage, titleBarCaption, '1', '2', 'Quit', '1');
if strcmpi(button, '1')
count = 1;
elseif strcmpi(button, '2')
count = 2;
elseif strcmpi(button, 'Quit')
break;
end
fprintf('Player %d selected %d\n',player,count);
theSum=theSum+count;
% Break out if the count >= 10.
if theSum >= 10
break;
end
% Switch to the next player.
player = rem(player, 2) + 1;
end
if theSum >= 10
message = sprintf('Player %d wins!\n',player);
fprintf('%s\n', message);
uiwait(helpdlg(message));
end

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by