Fortran隨機整數的生成

利用系統的random_number和random_seed函數生成隨機實數,再在此基礎上轉換成整數,

子程序Randi可以自定義隨機數的上下界。

Program main
    implicit none
    integer,allocatable::a(:)
    integer n,i
    integer min,max
    write(*,*) "Input the length of Array:"
    read(*,*) n
    write(*,*) "Input the range of Array(Min,Max):"
    read(*,*) min,max
    allocate(a(n))
    call RANDOM_SEED()
    do i=1,n
        call Randi(min,max,a(i))
    enddo
    
    write(*,*) "Array is created:"
    do i=1,n
        write(*,*) a(i)
    enddo
    deallocate(a)
    
    stop
    end

subroutine Randi(min,max,s)
    implicit none
    real x
    integer min,max,s
    call RANDOM_NUMBER(x)
    s=floor(x*(max-min+1))+min
    end


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章