本帖最后由 li913 于 2020-3-4 14:03 编辑
如果数组较大,建议直接用排序,然后统计。如果数组的取值范围较窄,可以直接开数组,用直接统计法。[Fortran] 纯文本查看 复制代码 !par20_ex7_t32
PROGRAM Vote32
! input constants
! N is the number votes
! M is maximum allowed number
INTEGER, PARAMETER :: N = 20, M = 4
INTEGER, PARAMETER :: sed = 42
! normal variables
INTEGER :: winner = 0, wincount = 0
INTEGER :: countnum_p = 0, countnum_n = 0
! votes is the input array
INTEGER, DIMENSION(N) :: votes
INTEGER, DIMENSION(-1:M) :: counts;
real ran
integer num(-2:5)
! init random number generator
call random_seed()
! init votes
DO i=1,N
call random_number(ran)
votes(i) = RAN * (M+3) - 2;
END DO
WRITE(*,"(A,100I3)") 'Input is: ', votes
! TODO
! find which was most voted number
wincount = 0
DO j=1,N
countnum_p = count(votes == votes(j))
if(wincount<countnum_p) then
wincount = countnum_p
winner = votes(j)
end if
END DO
WRITE(*,*) '个数: ', wincount
WRITE(*,*) 'Winner: ', winner
!直接统计法
num=0
do j=1,n
num(votes(j)) = num(votes(j)) + 1
end do
WRITE(*,*) '个数: ', maxval(num)
WRITE(*,*) 'Winner: ', maxloc(num)-1+lbound(num)
pause
END PROGRAM Vote32 |