Why are the elements of an array formatted as zeros when they are multiplied by 1/2 or 1/3?
I'm writing out the elements of an array as follows:
write(6,'(i4,200(1x,e15.7))')Jtot0, (a*PJjv(i,Jtot0,j,iv),i=1,nenerdif,100)
where a
is a constant. However, when this constant is equal to 1/2 or 1/3 the output is zeros, and if it's equal to 1, every thing goes well. The array elements are real*8
.
How can I overcome this, giving that I'm obligated to multiply by a factor of 1/3?
Solution 1:
In Fortran 1/2
is an integer division operation which will round down to, in this case, 0
. Same for 1/3
. If you want a real result, do a real division operation, such as 1.0/2.0
. Note that assigning the result of 1/2
to a real variable will set the real variable to 0.0
, that is the integer division will result in 0
and the assignment, which happens next, will cast that value to its nearest real representation.
This business of integer division producing integer results is very common in programming languages.