CEILING and FLOOR function in Fortran - aren't

2019-05-05 21:14发布

问题:

A quick question regarding the CEILING and FLOOR functions in Fortran 90/95.

Based on the documentation: https://gcc.gnu.org/onlinedocs/gfortran/CEILING.html

My impression is that they take in REALs, but return INTEGERs. However, as an example, for this simple program, I get:

PROGRAM example
REAL:: X=-3.4
nintx = NINT(x)
ceilx = CEILING(X)
floorx = FLOOR(X)
WRITE(*,*) nintx, ceilx, floorx
END PROGRAM

I get -3, -3.00000 and -4.00000. But based on the documentation all return types are INTEGERs. So why are the CEILING and FLOOR results displayed with the decimal point and trailing zeros?

回答1:

CEILING and FLOOR do return integer results. However, you are not printing those results: you are printing the variables celix and floorx which are of real type.

Those variables are real because of implicit typing. Contrast this with nintx which is indeed an integer variable.

List-directed output (the write(*,*) part) has as natural result formatting the real variables as you see. If you instead directly print the function results

write(*,*) NINT(x), CEILING(X), FLOOR(X)

you will be less surprised.

The obvious thing to say is: don't use implicit typing. Have as your second line implicit none.