Fortran系列:
判断语句
fortran的if语句,有if和end if包裹,判断条件后的执行语句,由then开启。下面做一个小函数,用于根据学生分数评价ABCD,即90分以上是A;80-90是B;60-80是C;不及格是D。
function grad2class(n) result(flag)
implicit none
real, intent(in) :: n
character :: flag
if (n>90) then
flag = "A"
else if (n>80) then
flag = "B"
else if (n>60) then
flag = "C"
else
flag = "D"
end if
end function grad2class
program ifTest
implicit none
real :: a = 95.5
character :: flag, grad2class
flag = grad2class(a)
print *, a, "is ", flag
end program ifTest
结果为
95.5000000 is A
select case语句
一般来说,家长得知孩子考了90多分,会很兴奋;如果考了80多分,差强人意,马马虎虎;如果六七十分,可能会有些不爽;如果不及格,那肯定就开喷了。
这个流程当然也可以用if…else来实现,但ABCD四个级别,彼此更加平等,用select case显然更加合理一些。
subroutine sayclass(flag)
implicit none
character :: flag
select case(flag)
case('A')
print *, "exciting"
case('B')
print*, "Good Luck"
case('C')
print*, "hehe"
case default
print*, "shit!!"
end select
end subroutine sayclass
program ifTest
call sayClass("D")
end program ifTest
运行结果为
>a.exe
shit!!
do循环
do循环有点像现代语言中的for循环,do i = m,n表示让i从m循环到n,类似于for(i=m; i<n; i++)。
program printNum
do i = 11, 20
print*, i
end do
end program printNum
然后就看到数字一行一行打印出来了。
while循环
这个while循环的形式是do while (condition),但其逻辑与C语言中的while循环是一致的,可以把do…end do理解为花括号。下面仍旧是打印数字的逻辑
program printNum
i = 11
do while (i <= 10)
print*, i
i = i+1
end do
end program factorial
exit, cycle, stop
在其他语言中,通过break可以跳出循环,通过continue可以跳过单次循环。fortran中起到这两个作用的关键字是exit和cycle。如果想做得更绝,可以使用stop终止整个程序,类似于C语言中的return。
program testCtrl
do i = 11, 15
if (i == 12) then
cycle
end if
print *, i
end do
doLoop:: do while(i<20)
i = i+1
if (i==18) then
exit doLoop
end if
print *, i
end do doLoop
do while(i<100)
i = i+1
if (i==22) then
stop
end if
print *, i
end do
end program testCtrl
结果如下,十分合理
11
13
14
15
17
19
20
21