条件循环是条件控制循环,适合循环次数不能预先确定、但每轮开始前必须判断条件的场景。
do while是循环前判断结构。每轮开始前先计算括号中的逻辑条件,条件为真才进入循环体,条件为假时结束循环。
- count和factorialValue在进入循环前都初始化为1。
- factorialValue=factorialValue*count累乘当前count。
- count=count+1使循环条件最终变为假,从而结束循环。
本文代码
! do while根据条件决定是否继续循环。
program doWhileDemo
implicit none
integer :: count
integer :: factorialValue
count=1
factorialValue=1
print "(A)","do while循环:"
do while (count<=5)
factorialValue=factorialValue*count
print "(A,I2,A,I4)","count=",count," 阶乘累计=",factorialValue
count=count+1
end do
end program doWhileDemo
编译运行
(base) hong@hongdeMacBook-Pro 026.doWhile % gfortran exampleDoWhile.f90
(base) hong@hongdeMacBook-Pro 026.doWhile % ./a.out
do while循环:
count= 1 阶乘累计= 1
count= 2 阶乘累计= 2
count= 3 阶乘累计= 6
count= 4 阶乘累计= 24
count= 5 阶乘累计= 120
结果分析
count从1开始,每轮先参与乘法再增加1,factorialValue依次得到1、2、6、24、120。
当count增加到6时,count不再满足不大于5的条件,程序不再进入下一轮。
知识点总结
- do while在每轮开始前判断逻辑条件。
- 循环体必须更新与条件有关的变量,本例更新的是count。
- 本例通过连续累乘计算1到5的阶乘累计值。