【发布时间】:2020-12-12 15:36:25
【问题描述】:
我正在编写一个计算 BMI 的 fortran 小代码,但我对 read 语句的 iostat 参数有一个问题。整个代码如下:
program calculate_bmi
! Simple BMI calculator
implicit none
character :: unit_system
character :: height_unit*15, weight_unit*10
real :: height, weight, bmi
integer :: ierror
print *, 'Would you like to use imperial or metric system?'
systemloop: do
print *, 'Press [I] for imperal system or press [M] for metric system.'
read *, unit_system
if (unit_system == 'i' .or. unit_system == 'I' .or. &
unit_system == 'm' .or. unit_system == 'M') exit systemloop
end do systemloop
if (unit_system == 'i' .or. unit_system == 'I') then
height_unit='inches'
weight_unit = 'pounds'
else
height_unit = 'centimeters'
weight_unit= 'kilograms'
end if
print *, 'Type in your height in ', height_unit
read (*, iostat = ierror) height
if (ierror /= 0) then
print *, 'Invalid input for height!'
call exit
end if
print *, 'Type in your weight in ', weight_unit
read (*, iostat = ierror) weight
if (ierror /= 0) then
print *, 'Invalid input for weight!'
call exit
end if
if (unit_system == 'i' .or. unit_system == 'I') then
bmi = 703 * weight / (height**2)
else
bmi = weight / ((height/100)**2)
end if
print *, 'Your BMI is: '
write (*, 1) NINT(bmi*10)/10.0
1 format(f6.1)
end program calculate_bmi
问题出现在这段代码:
print *, 'Type in your height in ', height_unit
read (*, iostat = ierror) height
if (ierror /= 0) then
print *, 'Invalid input for height!'
call exit
end if
print *, 'Type in your weight in ', weight_unit
read (*, iostat = ierror) weight
if (ierror /= 0) then
print *, 'Invalid input for weight!'
call exit
end if
iostat 总是将 5001 作为代码返回,并且 read 语句不会等待输入而只是终止程序。我做了一些谷歌搜索,但无法真正弄清楚到底是什么问题。如果我从 read 语句中删除 iostat,代码可以正常工作,但在这种情况下,我没有任何错误处理和防止错误输入的方式。
我对 fortran 有点陌生,所以请让我知道我在哪里犯了错误。我也使用 Gfortran 作为我的编译器。
【问题讨论】: