Fortran Coder

标题: 找数组中最大元素的个数以及位置 [打印本页]

作者: own2008    时间: 2020-3-3 16:05
标题: 找数组中最大元素的个数以及位置
新手第一次发帖,想问一下大佬我这个写的程序哪里错了,我用maxval 已经找到了数组中最大的元素,现在想求个数,但是一直显示
Array section designator, e.g. '(:)', is required besides the coarray designator '[...]' at (1) 不太理解
求问一下
代码如下
[Fortran] 纯文本查看 复制代码
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

! 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

winner = maxval(votes, dim=1, mask=(votes>0))
DO j=1,N
    if (votes == winner) then
        wincount = wincount + 1
END DO
!wincount = find(votes, winner)
!WRITE(*,*) 'Most votes was: ', wincount
WRITE(*,*) 'Winners were:   ', winner


END PROGRAM Vote32

作者: own2008    时间: 2020-3-3 16:06
就是从第30行开始有问题,其他的应该没问题
作者: kyra    时间: 2020-3-3 16:13
DO j=1,N
    if (votes == winner) then
        wincount = wincount + 1
END DO
改为
DO j=1,N
    if (votes(j) == winner) then
        wincount = wincount + 1
END DO
或者
wincount=count(votes == winner)
作者: own2008    时间: 2020-3-3 16:17
kyra 发表于 2020-3-3 16:13
DO j=1,N
    if (votes == winner) then
        wincount = wincount + 1

万分感谢!!!!
作者: own2008    时间: 2020-3-3 16:22
kyra 发表于 2020-3-3 16:13
DO j=1,N
    if (votes == winner) then
        wincount = wincount + 1

还有个问题如何找到数组中最多的元素呢
作者: kyra    时间: 2020-3-3 16:27
语法中没有这种函数,自己写循环统计吧




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