using while loops and random number generators
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Marina Christakos
le 24 Jan 2019
Modifié(e) : Kevin Phung
le 24 Jan 2019
var = 'y';
while (var=='y')
u=input('how many?', 's');
if (u > 0)
r = rand(1,u,'single');
randnum = ['Your Random Number Is:', num2str(r)];
disp(randnum);
var = input('Continue?', 's');
end
if (var ~='y')
disp('Program Terminated');
end
end
Problem asked to write a code where the user types a number (the amount of random numbers they want) and asked if they would like to continue generating random numbers (works if they type 'y'). If they type any other letter, the program is terminated. I've written this code for individual random numbers, but when i try to include the "how many" part, I get errors. I keep struggling with the r = rand(1,u,'single'); line. No matter how many times I change the code and try new things it doesn't work. How would I fix this error and allow the code to work properly?
0 commentaires
Réponse acceptée
Kevin Phung
le 24 Jan 2019
Modifié(e) : Kevin Phung
le 24 Jan 2019
you needed one more line:
var = 'y';
while (var=='y')
u=input('how many?', 's');
u = str2num(u); % u was a char, not a numeric.
if (u > 0)
r = rand(1,u,'single');
randnum = ['Your Random Number Is:', num2str(r)];
disp(randnum);
var = input('Continue?', 's');
end
if (var ~='y')
disp('Program Terminated');
end
end
note: you didnt need the 's' argument in input()
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Random Number Generation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!