如:我想产生20个随机数,但这20个随机数的总和为100?

解决方案 »

  1.   

    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  /
     
    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
     
      

  2.   

    不知道我的本意有没有表达清楚,比如我们年终考评的时候,总分可能是100分,总有有20个考核项,每个考核项有个考核系数。总分=sum(指标得分*考核系数)。sum(考核系数)应该是等于1的...我想要的也就是20个考核系数。
      

  3.   


    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;