using while loops and random number generators
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Marina Christakos
il 24 Gen 2019
Modificato: Kevin Phung
il 24 Gen 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 Commenti
Risposta accettata
Kevin Phung
il 24 Gen 2019
Modificato: Kevin Phung
il 24 Gen 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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Random Number Generation in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!