因此,我想编写一些代码,以使用户无法键入不在城市列表中的城市,city_list数组是大小为5的一维数组,其值分别为A,B,C,D和E. 所以我所做的就是这个
character, dimension(5) :: city_list
do i=1,5
city_list(i)= achar(i+64) !To give the array a,b,c values to its first five components
end do
character :: City1, ...
do while(ANY(City_list == City1) )
READ*, City1
PRINT*, "IT'S GOT TO BE A,B,C,D,E"
end do
所以我使用了我在另一篇文章中看到的ANY函数,但是我不能很好地使用它,它似乎没有按照我要求的去做
答案 0 :(得分:2)
所以我想通了,
do while(is_in_list .eqv. .FALSE.)
print*, "Introduce a city that is on the list"
READ*, Ciud1
do i=1, 5
if(city_list(i) == city1) then
is_in_list = .TRUE.
PRINT*, "It's in the list"
end if
end do
end do
这样,控制台将继续询问引入位于city_list中的城市。 一旦介绍了city_list中的内容,它将继续使用该代码。
我们可以整理一下这段代码,并使用ANY
函数:
is_in_list = .FALSE.
DO WHILE(.NOT.is_in_list)
PRINT*, "Introduce a city that is on the list"
READ*, city1
is_in_list = ANY(city_list==city1)
IF (is_in_list) PRINT*, "It's in the list"
END DO
这里:
.FALSE.
循环之前,将测试变量设置为DO
; .TRUE.
或.FALSE.
进行比较使我们看起来像脚本类,真正的程序员知道逻辑本身具有这些值之一; ANY
函数可以使编译器完成繁琐的工作; ANY
返回逻辑,我们可以将其结果直接分配给测试变量。答案 1 :(得分:2)
另一种方法可能是使用带条件exit
的无限do循环(使代码更简单...)
program main
implicit none
character :: city_list( 5 ), city1
city_list = ["A", "B", "C", "D", "E"]
do
print*, "Introduce a city that is on the list"
read *, city1
if ( any( city1 == city_list ) ) exit
enddo
print *, "Your city1 is ", city1
end
答案 2 :(得分:0)
!对于现代Fortran,您可以使用FINDLOC函数:
program TestFindLocinStringArray
implicit none
character:: city_list(5), city1
integer::ip(1)
city_list = ["A", "B", "C", "D", "E"]
print*, "Introduce a city that is on the list"
read *, city1
ip=findloc(city_list,city1)
if(ip(1)>0)then
type*,"city1 is on No#",ip
exit
else
type*, "Your city1 is NOT in the list!"
end if
enddo
end program