Reading REAL's from file in FORTRAN 77 - odd r

2019-07-30 16:03发布

问题:

I'm currently messing around in FORTRAN 77 and I've ran into a problem that I can't seem to figure out. I'm trying to read from a file that looks similar to below:

000120     Description(s) here       18     7     10.15
000176     Description(s) here       65     20    56.95
...

The last column in each row is a monetary amount (never greater than 100). I am trying to read the file by using code similar to below

          integer pid, qty, min_qty
          real price
          character*40 descrip

          open(unit=2, file='inventory.dat', status='old')
          read(2, 100, IOSTAT=iend) pid, descript, qty, min_qty, price
100       format(I11, A25, I7, I6, F5)

Everything seems to be read just fine, except for the last column. When I check the value of price, say for example, for the second line; instead of getting 56.95 I get something like 56.8999999999.

Now, I understand that I might have trailing 9's or whatnot because it's not totally precise, but shouldn't it be a little closer to 95 cents? Maybe there's something that I'm doing wrong, I'm not sure. Hopefully I'm just not stuck with my program running like this! Any help is greatly appreciated!

回答1:

Is that exactly the code you use to read the file? Do you have "X" formats to align the columns? Such as (I11, A25, 2X, I7, 3X, I6, 3X, F5) (with made up values). If you got the alignment off by one and read only "56.9" for "56.95", then floating point imprecision could easily give you 56.89999, which is very close to 56.9

You could also read the line into a string and read the numbers from sub-strings -- this would require only precisely identifying the location of the string. Once the sub-strings contained only spaces and numbers, you could use a less-finicky IO directed read: read (string (30:80), *) qty, min_qty, price.