Where should I add error checking to my program?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Jennifer Coss
il 15 Apr 2017
Commentato: Jennifer Coss
il 16 Apr 2017
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 Commenti
Risposta accettata
Image Analyst
il 15 Apr 2017
Modificato: Image Analyst
il 15 Apr 2017
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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Target Computer Setup in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!