Error when reading in float in Fortran

五迷三道 提交于 2021-01-20 07:26:26

问题


This should be quite simple, but I can't manage to read in a floating point number in Fortran. My program test.f looks like this:

  PROGRAM TEST
  open(UNIT=1,FILE='test.inp')
  read(1,'(f3.0)')line

  STOP
  END

The input file test.inp simply contains a single float: 1.2

Now the compiling of my testfile goes fine, but when I run it I get an error:

At line 4 of file test.f (unit = 1, file = 'test.inp')

Fortran runtime error: Expected REAL for item 1 in formatted transfer, got INTEGER

(f3.0)

^

I've tried different modifications of the code and also googling for the error message, but with no result. Any help would be greatly appreciated!

Regards, Frank


回答1:


Your variable line is implicitly defined as integer. This doesn't work with thef edit descriptor. If you want to read an integer use i edit descriptor (i3 for example). Otherwise declare line as real to math the "f" descriptor.

Note beside: the .0 is not a problem, because if Fortran gets a number with decimal point the .0 part in the descriptor is ignored. It is only used when an number without a decimal is entered and then it uses the number behind the decimal point in the desciptor to add a decimal point into the right place. For with F8.5, 123456789 is read as 123.45678. More ont this here http://software.intel.com/sites/products/documentation/hpc/compilerpro/en-us/fortran/lin/compiler_f/lref_for/source_files/pghredf.htm .




回答2:


In your read statement

read(1,'(f3.0)')line

the f3.0 tells tour program to read 3 digits with 0 digits after the decimal (this is what the n.m syntax means). So I presume that the program is just reading 1 from the file (not 1.2), which is an integer. Try replacing that line with something like

read(1,'(f3.1)')line

although, if the number in your file is likely to change and be larger than 9.9 or have more than one decimal place you should increase the field width to something larger than 3.

See the documentation of the read intrinsic and for data edit descriptors for more information on reading and writing in Fortran.

Edit: the format specifier, the second argument in quotes in your read statment, has the form fw.d, where f indicates that the data to read is a floating point number, w is the width of the field including all blanks and decimal points and d specifies the number of digits to the right of the decimal point.




回答3:


I would suggest reading/writing list formatted data, unless you have a very strong reason to do otherwise. assuming that you're reading in from a file with just a single float or integer in a single line, like this

123.45
11
42

then this should do the reading

real*8 :: x,y,z
open(1,file=filename)
read(1,*)x
read(1,*)y
read(1,*)z
close(1)


来源:https://stackoverflow.com/questions/8477010/error-when-reading-in-float-in-fortran

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!