SQL> declare 2 type num_type is table of number; 3 num_arr num_type:=num_type(); 4 n number:=0; 5 begin 6 for i in 1 ..20 loop 7 num_arr.extend; 8 select round(dbms_random.value(1,100)) into num_arr(i) from dual; 9 end loop; 10 for j in 1..num_arr.count loop 11 dbms_output.put_line(num_arr(j)||' '||num_arr.count); 12 end loop; 13 end; 14 /
declare type num_type is table of number; num_arr num_type:=num_type(); n number:=0; x number := 100; begin -- 循环处理20个数 for i in 1 ..20 loop -- 扩展数组 num_arr.extend; -- 如果是最后一个数,则不需要随机(因为和为100,所以只能随机19个数) if i = 20 then num_arr(i) := x; -- 前19个数进行随机生成,因为要给后面的数保留值,所以只能在x - (20 -i) * 2中取值 else select round(dbms_random.value(1,x - (20 - i)*2)) into num_arr(i) from dual; end if; -- 计算剩余的可取值范围 x := x - num_arr(i); -- 输出显示 dbms_output.put_line(i||' '||num_arr(i)); end loop;
2 type num_type is table of number;
3 num_arr num_type:=num_type();
4 n number:=0;
5 begin
6 for i in 1 ..20 loop
7 num_arr.extend;
8 select round(dbms_random.value(1,100)) into num_arr(i) from dual;
9 end loop;
10 for j in 1..num_arr.count loop
11 dbms_output.put_line(num_arr(j)||' '||num_arr.count);
12 end loop;
13 end;
14 /
PL/SQL procedure successfully completed
SQL> set serveroutput on
SQL> /
59 20
9 20
51 20
3 20
92 20
22 20
13 20
4 20
30 20
46 20
48 20
75 20
77 20
75 20
46 20
61 20
63 20
92 20
28 20
20 20
PL/SQL procedure successfully completed
declare
type num_type is table of number;
num_arr num_type:=num_type();
n number:=0;
x number := 100;
begin
-- 循环处理20个数
for i in 1 ..20 loop
-- 扩展数组
num_arr.extend;
-- 如果是最后一个数,则不需要随机(因为和为100,所以只能随机19个数)
if i = 20 then
num_arr(i) := x;
-- 前19个数进行随机生成,因为要给后面的数保留值,所以只能在x - (20 -i) * 2中取值
else
select round(dbms_random.value(1,x - (20 - i)*2)) into num_arr(i) from dual;
end if;
-- 计算剩余的可取值范围
x := x - num_arr(i);
-- 输出显示
dbms_output.put_line(i||' '||num_arr(i));
end loop;
end;