Continue a loop when entered an option

In my code I want to begin the loop again when I enter 1 and quit the program when entered 0.
clc
clear
syms result guess
corrects = 0;
n = 10;
for k = 1:n
x = randi([3 10],1,1);
y = randi([3 10],1,1);
result = x * y;
guess = input(sprintf('What is %d * %d?: ', x,y));
if (result == guess)
disp('Correct!')
corrects = corrects + 1;
else
fprintf('Wrong! The correct answer is %d\n', result);
end
end
fprintf('You were right %d out of 10!\n', corrects);
option = input('Do you want to do a new round (1 = yes, 0 = no): ');
if option == '1'
%start the loop again otherwise quit
end

回答(1 个)

Just wrap your code in a while loop:
option = 1;
while option == 1
%... your code here
option = input('Do you want to do a new round (1 = yes, 0 = no): ');
end
Any reason you're using the symbolic toolbox? As far as I can tell it's completely unneeded.

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by