Note that there are some explanatory texts on larger screens.

plurals
  1. POFortran: How do I read the first character from each line of a text file?
    primarykey
    data
    text
    <p>this is my first time trying to program in Fortran. I'm trying to write a program that prints the first 1476 terms of the <a href="http://en.wikipedia.org/wiki/Fibonacci_number" rel="nofollow noreferrer">Fibonacci sequence</a>, then examines the first digit of each term and stores the number of 1s, 2s, 3s, ..., 9s that occur in an array.</p> <p>The problem that I can't seem to figure out is how to read the first digit of each term. I've tried several things but am having difficulty with my limited knowledge of Fortran techniques. I write the terms to a text file and the idea is to read the first digit of each line and accumulate the respective number in the array. Does anyone have any suggestions of how to do this? </p> <p>Here is my code so far:</p> <p>(<strong>edit</strong>: I included the code I have for reading the file. Right now it just prints out 3.60772951994415996E-313, which seems like an address of some sort, because it's not one of the Fibonacci numbers. Also, it is the only thing printed, I expected that it would print out every line of the file...)</p> <p>(<strong>edit edit</strong>: After considering this, perhaps there's a way to format the writing to the text file to just the first digit. Is there a way to set the number of significant digits of a real number to one? :P)</p> <pre><code>subroutine writeFib(n) integer :: i real*8 :: prev, current, newFib prev = 0 current = 1 do i = 1, n newFib = prev + current prev = current current = newFib write(7,*) newFib end do return end subroutine subroutine recordFirstDigits(a) integer :: openStat, inputStat real*8 :: fibNum open(7, file = "fort.7", iostat = openStat) if (openStat &gt; 0) stop "*** Cannot open the file ***" do read(7, *, iostat = inputStat) fibNum print *,fibNum if (inputStat &gt; 0) stop "*** input error ***" if (inputStat &lt; 0) exit ! end of file end do close(7) end subroutine program test integer :: k, a(9) k = 1476 call writeFib(k) call recordFirstDigits(a) end program </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload