Error when reading in float in Fortran

后端 未结 3 845
情深已故
情深已故 2021-01-20 16:48

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
  ope         


        
相关标签:
3条回答
  • 2021-01-20 17:05

    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)
    
    0 讨论(0)
  • 2021-01-20 17:08

    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.

    0 讨论(0)
  • 2021-01-20 17:29

    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 .

    0 讨论(0)
提交回复
热议问题