Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

io - 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...