Fortran Coder

标题: 找数组中最多的元素以及其个数,为什么没有计算0的值 [打印本页]

作者: own2008    时间: 2020-3-3 16:48
标题: 找数组中最多的元素以及其个数,为什么没有计算0的值
想了一个方法但是只找到了非0元素中最多的元素以及其个数,不太理解为什么
[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 :: seed = 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;

! init random number generator
i = RAND(seed)

! init votes
DO  i=1,N
    votes(i) = RAND() * (M+3) - 2;
END DO

WRITE(*,"(A,100I3)") 'Input is: ', votes

! TODO
! find which was most voted number

DO j=1,N-1
    countnum_p = count(votes == votes(j))
    countnum_n = count(votes == votes(j+1))
    if (countnum_n > countnum_p) then
        winner = countnum_n
        wincount = votes(j+1)
    else
        winner = countnum_p
        wincount = votes(j)
    END if
END DO


WRITE(*,*) 'Most votes was: ', wincount
WRITE(*,*) 'Winners were:   ', winner


END PROGRAM Vote32





作者: own2008    时间: 2020-3-3 16:49
仍然是在第31行开始,为什么没有统计到0的个数呢
作者: own2008    时间: 2020-3-3 17:00
我用了一种比较偷懒的方式,直接先计算0的个数然后最后再和这个比较,但还是不太明白这个count计数为什么没有把0算进去,求大佬解答一下
[Fortran] 纯文本查看 复制代码
INTEGER :: countnum_p = 0, countnum_n = 0, countnum_z = 0
if (countnum_z >winner) then
    winner = countnum_z
        wincount = 0
END if

作者: necrohan    时间: 2020-3-3 23:07
if (countnum_n > countnum_p) then
这句的意思是一个数的出现次数大于后一个数的次数则保存前一个数的出现次数和数值,不是保存最多的元素以及其个数。
如果有2个数出现的次数并列第一,楼主也没有考虑
作者: li913    时间: 2020-3-4 13:51
本帖最后由 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





欢迎光临 Fortran Coder (http://bbs.fcode.cn/) Powered by Discuz! X3.2