FortranTip icon indicating copy to clipboard operation
FortranTip copied to clipboard

Tip: integer division

Open Beliavsky opened this issue 2 years ago • 1 comments

Given integer variables i and j write

real(i,wp)/j or i/real(j,wp) or real(i,wp)/real(j,wp)

where wp is the KIND argument to get a real(kind=wp) quotient, unless you want the truncating integer division resulting from

i/j

In Fortran 1/2 = 0.

Beliavsky avatar Feb 13 '22 00:02 Beliavsky

Possibly a better way to write the same statement:

When dividing two integer numbers, you will get a truncated integer, not a real number, so 1/2 is 0 (gfortran will warn about this with -Wall, but for constants only).

If what you really want is the real number, write real(i,wp)/j , i/real(j,wp), ...

tkoenig1 avatar Feb 13 '22 10:02 tkoenig1