Write a function called mathgame.m that repeatedly asks a user to answer a simpl
ID: 3551691 • Letter: W
Question
Write a function called mathgame.m that repeatedly asks a user to answer a simple addition question. After each question the user is told if their answer is correct or incorrect and they are given the opportunity to continue or to stop. When they stop a summary of their results for the game is provided.
Tackle this problem in small pieces. The following is a suggested strategy but certainly not the only one:
Create two random integers between 1 and 10 and store them in separate variables.
Compute the sum of the two integers and store the result in another variable.
Output the question so the user can see the two random numbers but can not see the result of the sum operation.
Prompt the user to enter their guess and collect it using the input function.
Determine if the user
Explanation / Answer
function mathgame = mathgame()
disp('Welcome to the math game!');
count = 1;
correct = 0;
incorrect = 0;
rand1 = 1 + 9 * rand(1);
rand2 = 1 + 9 * rand(1);
sprintf("%d: %d + %d =",count,rand1,rand2);
answer = input('');
if answer == rand1+rand2
disp('Correct!');
correct = correct +1;
else
disp('Incorrect!');
incorrect = incorrect+1;
end
again = input('Again','s');
while strcmp(again,'y')==1
count = count+1;
rand1 = 1 + 9 * rand(1);
rand2 = 1 + 9 * rand(1);
sprintf("%d: %d + %d =",count,rand1,rand2);
answer = input('');
if answer == rand1+rand2
disp('Correct!');
correct = correct +1;
else
disp('Incorrect!');
incorrect = incorrect+1;
end
again = input('Again','s');
end
sprintf('Correct: %d (%.2f %%), Incorrect %d (%.2f %%)',correct,(100.0*correct/count),incorrect,(100.0*incorrect/count))
end
mathgame();
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.