How to generate random number within a sum limit?

9 次查看(过去 30 天)
Generate 5 random numbers, where their sum should be less/equal to 50.

采纳的回答

Birdman
Birdman 2017-11-7
while true
A=randi([1 15],5,1);
if(sum(A)<=50)
break;
end
end
disp(A)
disp(sum(A))
  2 个评论
Arnab Pal
Arnab Pal 2017-11-7
ok, it is working. But I need decimal number also. It is giving the only integer. Thank u
Birdman
Birdman 2017-11-7
编辑:Birdman 2017-11-7
while true
t=15;
A=t*rand(5,1);
if(sum(A)<=50)
break;
end
end
disp(A)
disp(sum(A))
You can change t.

请先登录,再进行评论。

更多回答(1 个)

Roger Stafford
Roger Stafford 2017-11-7
If the numbers are supposed to be any five positive integers, do this:
b = true;
while b
x = 50*randi(5,1);
b = sum(x)>50;
end
If the numbers can be any non-negative real numbers, change the third line above to:
x = 50*rand(5,1);

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by