using while loops and random number generators
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Marina Christakos
el 24 de En. de 2019
Editada: Kevin Phung
el 24 de En. de 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 comentarios
Respuesta aceptada
Kevin Phung
el 24 de En. de 2019
Editada: Kevin Phung
el 24 de En. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Random Number Generation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!