Where should I add error checking to my program?
1 次查看(过去 30 天)
显示 更早的评论
I'm trying to create a program that simulates a dice roll. The instructions given are: Write a matlab funtion called hitTarget that will accept one scalar argument, the target sum of two random 6-sided dice rolls. The function generates and displays two random numbers between 1 and 6 (like dice rolls) until the sum of the two die equals the target argument. Keep track of how many rolls it takes.
Sample Run:
>> hitTarget(8)
5 2
6 3
2 2
4 3
3 5
Target met, it took 5 rolls.
My code so far:
function [] = hitTarget( target )
%if(target>=2 && target<=12 && isinteger(target))
count = 0;
dieTotal = 0;
while(dieTotal~=target)
count = count + 1;
dieOne = randi(6,1,1);
dieTwo = randi(6,1,1);
result = [dieOne dieTwo];
disp(result);
dieTotal = sum(result);
if(dieTotal==target)
disp(['Target met, it took ', num2str(count), ' rolls.']);
end
end
%end
end
I commented out the error checking statement I need because the program will not run at all if I leave it there. But I don't know where else to put it.
Thanks for any help!!!
0 个评论
采纳的回答
Image Analyst
2017-4-15
编辑:Image Analyst
2017-4-15
Replace the line
%if(target>=2 && target<=12 && isinteger(target))
with
if target<2 || target > 12
errorMessage = sprintf('A target of %d is not allowed.\n', target);
uiwait(errordlg(errorMessage));
return;
end
if ~isinteger(target)
errorMessage = sprintf('Fractional numbers are not allowed!');
uiwait(errordlg(errorMessage));
return;
end
% If it gets here, the target number is acceptable.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Target Computer Setup 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!