using while loops and random number generators

4 次查看(过去 30 天)
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?

采纳的回答

Kevin Phung
Kevin Phung 2019-1-24
编辑:Kevin Phung 2019-1-24
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 个)

类别

Help CenterFile Exchange 中查找有关 Random Number Generation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by