문제

I need to find how to use the dimension attribute in this program. The problem in here that I can't figure out is how user can specify the number of rows? (another word, the number of students):

PROGRAM 
implicit none

integer::k,sn
real,dimension(**?**,4)::A
character(len=10),dimension(**?**)::B

open(10,file='students.txt',status='new')
write(*,*)'how many student are in the classroom?'
read(*,*)sn 
k=1 

do 
    write(*,*)k,'.','student name=';read(*,*)B(k)
    write(*,*)'1.Quiz';read(*,*)A(k,1)
    write(*,*)'2.Quiz';read(*,*)A(k,2)
    write(*,*)'Final Quiz';read(*,*)A(k,3)


    A(k,4)=(A(k,1)*30/100)+(A(k,2)*30/100)+(A(k,3)*40/100)

    write(10,9)B(k),'     ',A(k,1),'   ',A(k,2),'   ',A(k,3),'   ',A(k,4)

    k=k+1
    if(k>sn)exit

end do
9 format(1x,A10,A5,F5.1,A3,F5.1,A3,F5.1,A3,F5.1)  
end program 
도움이 되었습니까?

해결책

Well basically you have fixed (static) arrays which are defined e.g. using dimension:

real,dimension(4) :: X

X is an array of length 4 (1-4). This is equivalent to:

real :: X(4)

Static arrays have a fixed length throughout their scope (e.g. throughout the program for global variables or throughout functions/subroutines).

What you need are allocatable arrays which are allocated at runtime:

program test
  implicit none
  real, allocatable :: B(:) ! The shape is given by ":" - 1 dimension
  integer           :: stat

  ! allocate memory, four elements: 
  allocate( B(4), stat=stat )
  ! *Always* check the return value
  if ( stat /= 0 ) stop 'Cannot allocate memory'

  ! ... Do stuff

  ! Clean up
  deallocate( B )

  ! Allocate again using a different length:
  allocate( B(3), stat=stat )
  ! *Always* check the return value
  if ( stat /= 0 ) stop 'Cannot allocate memory'

  ! No need to deallocate at the end of the program! 

end program

다른 팁

real,dimension(:,:),allocatable ::A

character(len=10),dimension(:),allocatable::B
.
.
.
 DEALLOCATE(A)
          DEALLOCATE(B)

This works! Thank you guys.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top