Help with while loop programming
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Angel Washington
am 25 Mär. 2020
Bearbeitet: Angel Washington
am 25 Mär. 2020
1)Add code that repeatedly prompts the user for a classification number, an integer from 1 to 4, until the user enters a valid classification number. Hint: use the floor() function to test for an integer value.
I made this program, but it only gives 0 or 1 and does not show disp
How can I fix this to show disp?
%this function will repeatedly prompt the user for a classification number
%until the user enters a valid classification number
classification = input('Enter your classification as an interger from 1 to 4: ');
TF = (5 > classification) && (classification > 0)
while (5 > classification) && (classification > 0) == 0
disp('INVALID INPUT - the number entered is not a valid classification number');
classification = input ('Please re-enter your classification as an interger from 1 to 4: ');
if (5 > classification) && (classification > 0) == 1
disp(classification)
disp('The interger entered is a valid classification number');
end
end
2)Add code that repeatedly displays a random integer from 1 to 6 (the roll of a die) until the first number displayed is redisplayed. Thus, numbers after the first number may be repeated any number of times, but the first number will be repeated exactly once. Hint: use the following expression to get a random integer from 1 to 6: floor(rand()*6) + 1
I am completely lost with this question
0 Kommentare
Akzeptierte Antwort
Fangjun Jiang
am 25 Mär. 2020
Almost there! Give it a meaningful but not confusion variable name, and don't repeat the same calculation.
%this function will repeatedly prompt the user for a classification number
%until the user enters a valid classification number
classification = input('Enter your classification as an interger from 1 to 4: ');
IsValid = (5 > classification) && (classification > 0);
while ~IsValid
disp('INVALID INPUT - the number entered is not a valid classification number');
classification = input ('Please re-enter your classification as an interger from 1 to 4: ');
IsValid = (5 > classification) && (classification > 0);
if IsValid
disp(classification)
disp('The interger entered is a valid classification number');
end
end
3 Kommentare
Fangjun Jiang
am 25 Mär. 2020
Very similar to this one. Roll the dice once, remember this "first number", then keep rolling the dice till the number rolled is the same as the "first number".
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Direct Search finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!