While loop???

Write a script that generates a random integer number between 1 and 10 (you will need to use rand and round(...)functions. Prompt player to guess number. Using a while loop, continue prompting the user until the correct number is guessed. Output both the correct number and the number of guesses.
ask=input('Enter a number between 1 and 10:');
number=1+round(rand*(9));
total=0;
while ask~=number
if(number<1 || number>10);
disp('Invalid')
total=guess+1;
ask=input('Enter a number between 1 and 10:');
else
if(ask==number)
fprintf('% is correct',ask);
else
fprintf('%is incorrect',ask);
guess=input('Enter a number between 1 and 10:');
end
total=total+1;
end
end
fprintf('Your answer is correct %g',ask==number);

 Risposta accettata

bym
bym il 13 Ott 2011

0 voti

I didn't know where to start, so look at this. I tried to preserve your code as much as possible
[edit]
clc;clear
number=1+round(rand*(9));
guess = 0;
total=0;
while guess~=number
if(guess<1 || guess>10);
disp('Invalid')
% removed elseif case here based on Fangjun's comment
else
disp('incorrect, guess again');
end
total=total+1;
guess = input('Enter a number between 1 and 10:');
end
fprintf('You guessed the correct number %g in %g attempts\n',guess,total);

5 Commenti

Fangjun Jiang
Fangjun Jiang il 13 Ott 2011
I think "elseif(guess == number)" is not needed.
bym
bym il 13 Ott 2011
@Fangjun
you are correct, it has been a long day. I'd vote for you comment :)
Fangjun Jiang
Fangjun Jiang il 13 Ott 2011
That's all right. It's a homework assignment. But the OP has shown enough effort.
Sean
Sean il 13 Ott 2011
Thank you for your help. I really appreciate it.
Fangjun Jiang
Fangjun Jiang il 13 Ott 2011
One more challenge, as of now, it always display 'Invalid' at the beginning. How to eliminate that message or any other invalid message?

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Richiesto:

il 12 Ott 2011

Community Treasure Hunt

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

Start Hunting!

Translated by