我只是想听听别人的意见。我是gfortran的新手,我有以下代码:
program Assignmenttwo
!Nik Wrye
!CDS251-001
!Homework #2/Assignment #2
!September 9th, 2021
!This program is to Next, write a do loop that iterates 10 million
!times. In the loop, add 1.e-7 (one ten-millionth) to each variable (The variable should
!appear on both sides of the equal sign.) After the loop, print out each variable with
!a label.
implicit none
!declaring variables
real*4:: Numone, Numtwo
!intializing variables
Numone = 1.0
Numtwo = 2.0
do while (Numone < 1.1.and.Numtwo<2.1)!this do statement will cycle the loop until it has it the 10 millionth time
Numone = Numone+1.e-7 !adding the desired amount
Numtwo = Numtwo+1.e-7
enddo
print*, Numone
print*, Numtwo
end program Assignmenttwo
我期望输出是1.1和2.1,但我得到1.1和2.0。什么好主意吗?
可以说,这个任务的重点是你得到了1.1
,但2.0
。这是由于浮点数的行为,其详细信息可以在其他地方阅读。
你可以做一个简单的测试
print *, 1.+1e-7, 2.+1e-7
print *, 1.+1e-7/=1., 2.+1e-7/=2.
不做循环看效果
与其重复关于机制的大量细节,我只想说你可以确认1e-7"太小了"。利用nearest
内禀函数
print *, nearest(2., 1.)
使用双精度,您将得到不同的答案。(这就是为什么在任何情况下仔细考虑使用哪种实际类型是很重要的。)
不要忘记Fortran不再允许真正的DO控制,因为增量可能太小而没有效果。