integer, do loop, fortran, error

被刻印的时光 ゝ 提交于 2019-12-02 09:08:06

Many people have already pointed this out in the comments to your question, but here it is again as an answer:

In Fortran, if you do a division of two integer values, the result is an integer value.

6/3 = 2

If the numerator is not evenly divisible by the denominator, then the remainder is dropped:

7/3 = 2

Let's look at your code:

q=floor(n/2)

It first evaluates n/2 which, since both n and 2 are integers, is such an integer division. As mentioned before, this result is an integer.

This integer is then passed as argument to floor. But floor expects a floating point variable (or, as Fortran calls it: REAL). Hence the error message:

"[The] argument of floor ... must be REAL."

So, the easiest way to get what you want is to just remove the floor altogether, since the integer division does exactly what you want:

q = n/2 ! Integer Division

If you need to make a floating point division, that is if you want two integer variables to divide into a real variable, you have to convert at least one of them to floating point before the division:

print *, 3/2           ! wrong, prints 1
print *, real(3)/2     ! right
print *, 3/2.0         ! right
print *, (3 * 1.0) / 2 ! right
print *, real(3/2)     ! wrong, prints 1.0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!