using while loops and random number generators
5 views (last 30 days)
Show older comments
Marina Christakos
on 24 Jan 2019
Edited: Kevin Phung
on 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 Comments
Accepted Answer
Kevin Phung
on 24 Jan 2019
Edited: Kevin Phung
on 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 Comments
More Answers (0)
See Also
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!