您可以从下面的代码中看到,当它询问您是继续还是停止该程序时,请按其他键,例如“;”。或“”,它会像按了“ Y”或“ y”键一样显示,但没有按。所以,我问这是编译器中的错误还是代码有问题?
program vols
!Calculates difference in volume of 2 spheres
implicit none
real :: rad1,rad2,vol1,vol2
character :: response
do
print *, 'Please enter the two radii'
read *, rad1,rad2
call volume(rad1,vol1)
call volume(rad2,vol2)
write(*,10) 'The difference in volumes is, ',abs(vol1-vol2)
10 format(a,2f10.3)
print *, 'Any more? - hit Y for yes, otherwise hit any key'
read *, response
if (response /= 'Y' .and. response /= 'y') stop
end do
end program vols
!________________________________________________
subroutine volume(rad,vol)
implicit none
real :: rad,vol,pi
!calculates the volume of a sphere
pi=4.0*atan(1.0)
vol=4./3.*pi*rad*rad*rad
!It's a little quicker in processing to do r*r*r than r**3!
end subroutine volume
FYI-我在Intel Fortran中尝试了此代码,它可以按预期工作。当response
为y
或Y
时,它将循环播放,否则退出循环。
program vols
!Calculates difference in volume of 2 spheres
implicit none
real :: rad1,rad2,vol1,vol2
character :: response
do
print *, 'Please enter the two radii'
read *, rad1,rad2
call volume(rad1,vol1)
call volume(rad2,vol2)
print '(a,2f10.3)', 'The difference in volumes is, ',abs(vol1-vol2)
print *, 'Any more? - hit Y for yes, otherwise hit any key'
read *, response
if (response /= 'Y' .and. response /= 'y') stop
end do
contains
subroutine volume(rad,vol)
implicit none
real :: rad,vol,pi
!calculates the volume of a sphere
pi=4.0*atan(1.0)
vol=4./3.*pi*rad*rad*rad
!It's a little quicker in processing to do r*r*r than r**3!
end subroutine volume
end program vols
所以看来,这里的问题可能特定于gfortran
。
PS。我将函数移到了program
块中,因此它不需要接口或外部声明。
PS2。我检查了编译结果,并且rad**3
与rad*rad*rad
相同。现代编译器比您想象的要聪明。最好在程序中显示intent,而不是用微优化来掩盖它。
没有您确切输入的更多详细信息,我们无法得出结论,这是gfortran中的错误。而是,程序的某个功能可能导致“令人困惑”的行为。
为了获得响应,程序使用列表定向输入。这导致不直观的结果。例如,对于someone writing a calculator,当有人输入*
或/
时会发生什么会感到惊讶。
在计算器示例中,*
涉及重复计数,/
涉及记录分隔符。对于此问题,,
也具有特殊含义。在列表导向的输入中,,
是值分隔符,并且用该字符显示的read *, x
不会将x
设置为值','
。
代替输入语句
read *, response
当出现输入时
,
将来到,
并看到“哈哈,用户告诉我没有指定值”。这与空行形成对比,在空行中,输入处理继续等待一个值。
此值分隔符与列表定向输入的另一个功能结合:允许使用空值。空值将完成输入语句,但保留相应的值unchanged(不设置为空白)。
这意味着如果输入类似
1 1
y
1 1
,
在第二遍中,字符response
从值'y'
起未更改。同样,对于
1 1
,
[response
]与未定义状态保持不变:不允许程序将其值与'y
'进行比较。
如何解决?只需使用适当的格式:
read '(A)', response
以这种方式,将输入,
视为字符而不是值分隔符。