If statement 计算文件中相等的行数
假设您有以下格式的file.dat:If statement 计算文件中相等的行数,if-statement,fortran,fortran90,gfortran,If Statement,Fortran,Fortran90,Gfortran,假设您有以下格式的file.dat: 1 1 1 2 2 3 3 3 3 ... 我想数一数有多少个相等的数字,并将它们迭代地保存在一个字符串中。例如: m = 3 (times 1), m = 2 (times 2), m = 4 (times 3). 我把代码放在这里: program sele implicit none integer::j,k,s,n,l,r,m real*8,allocatable::ID(:)
1
1
1
2
2
3
3
3
3
...
我想数一数有多少个相等的数字,并将它们迭代地保存在一个字符串中。例如:
m = 3 (times 1),
m = 2 (times 2),
m = 4 (times 3).
我把代码放在这里:
program sele
implicit none
integer::j,k,s,n,l,r,m
real*8,allocatable::ID(:)
real*8:: j_r8,i_r8
open(10,file='data.dat')
n=0
DO
READ(10,*,END=100)
n=n+1
END DO
100 continue
rewind(10)
allocate(ID(n))
s=0
do s=1, n
read(10,*) ID(s)
end do
do r=1,n-1
if (ID(r)-ID(r+1) .EQ. 0) then
m = m + 1
print*, m
end if
end do
end program
最后一个do
是我想要扩展的条件,类似于:
if (condition is true) then
save an index of the number of equal digits
use this to do some operations:
i=1,相等位数吗
如果(条件不正确),则
用其他数字重新启动。如果要读取的值是给定有限范围内的整数值(例如从1到100),则最简单的方法如下:
program sele
implicit none
integer, parameter :: vmin=1
integer, parameter :: vmax=100
integer :: list(vmin:vmax)
integer :: value,i
open(10,file='data.dat')
list=0
do
read(10,*,end=10) value
if(value < vmin .OR. value > vmax) then
write(*,*) 'invalid value ',value
stop
endif
list(value)=list(value)+1
enddo
10 continue
do i=vmin,vmax
if(list(i) > 0) then
write(*,*) list(i),' times ',i
endif
enddo
end program
可以很容易地改进该程序以管理变量vmin和vmax(然后必须声明数组列表可分配并以正确的大小分配)。
如果范围太大,那么一个简单的数组就不再精确,正确的算法也变得更加复杂:它必须避免存储未使用的值。我不得不承认,我形成了这样一种观点,即您试图完全通过问答来学习Fortran,诸如此类。我认为,为了你自己的利益,你应该更加努力地解决你自己的问题。例如,这是一个非常简单的问题。踢开拐杖走路。一、 首先,我不会再帮你了。就像你今天的另一个问题一样,你不是真正的Fortran问题,而是一个算法问题。我认为你尝试学习Fortran是件好事(即使在这里,它也不一定是最有效的),但我认为你也应该在编程方面工作。我的意思是:“我想做什么?”以及“我怎样用Fortran做?”。
3 times 1
2 times 2
4 times 3