2012-08-29 115 views
1

我是Fortran编程的新手。我有两个.f90文件。Fortran 90,函数,数组

fmat.f90

function fmat(t,y) 
implicit none 
real::t 
real::y(2) 
real::fmat(2) 
fmat(1) = -2*t+y(1) 
fmat(2) = y(1)-y(2) 
end function fmat 

而且,main.f90时的样子:

program main 
implicit none 
real::t 
real::y(2) 
real::fmat(2) 
real::k(2) 
t=0.1 
y(1)=0.5 
y(2)=1.4 
k=fmat(t,y) 
write(*,*) k 
end program main 

所以,我期待0.3 -0.9。但我不断收到以下错误消息:

ifort fmat.f90 main.f90 

main.f90(13): error #6351: The number of subscripts is incorrect. [FMAT] 
k=fmat(t,y) 
--^ 
compilation aborted for main.f90 (code 1) 

任何帮助表示赞赏!

!==== ====编辑

我感谢马克对他的答案。我实际上可以使用“子程序”方法编译单独的文件而不出现任何错误。

main.f90时

program main 
    implicit none 
    real::t 
    real::y(2) 
    real::k(2) 
    t=0.1 
    y(1)=0.5 
    y(2)=1.4 
    call fmat_sub(t,y,k) 
    write(*,*) k 
end program main 

fmat_sub.f90

subroutine fmat_sub(t,y,k) 
    implicit none 
    real::t 
    real::y(2),k(2) 
    k(1) = -2*t+y(1) 
    k(2) = y(1)-y(2) 
end subroutine fmat_sub 
+0

现在尝试在'main'中用'call fmat_sub(t,y)'行调用fmat_sub(t,y,k)'行,看看结果如何。 –

回答

5

你的声明,在main,的real::fmat(2)告诉编译器fmat是实数的与阵列秩1和长度2.并没有告诉任何有关在其他文件中写入的函数fmat的任何信息。

避免此类问题的一个好方法是使用现代Fortran的功能。把你的子程序和函数放入模块使用关联他们。因此,改变fmat.f90为类似

module useful_functions 

contains 
function fmat(t,y) 
implicit none 
real::t 
real::y(2) 
real::fmat(2) 
fmat(1) = -2*t+y(1) 
fmat(2) = y(1)-y(2) 
end function fmat 

end module useful_functions 

和修改main.f90喜欢的东西

program main 
use useful_functions 
implicit none 
real::t 
real::y(2) 
real::k(2) 
t=0.1 
y(1)=0.5 
y(2)=1.4 
k=fmat(t,y) 
write(*,*) k 
end program main 

这种方法可以让编译器生成明确的接口的模块功能,并允许它来检查,在编译时,虚拟参数实际参数之间的匹配。

既然你是新手,我已经把一些关键术语用斜体表示出来,在你的编译器手册或其他最喜欢的Fortran文档中阅读它们。

另一种方法来解决你的问题将是编辑main.f90到包括功能fmat源,如:

program main 
implicit none 
real::t 
real::y(2) 
real::k(2) 
t=0.1 
y(1)=0.5 
y(2)=1.4 
k=fmat(t,y) 
write(*,*) k 

contains 

function fmat(t,y) 
implicit none 
real::t 
real::y(2) 
real::fmat(2) 
fmat(1) = -2*t+y(1) 
fmat(2) = y(1)-y(2) 
end function fmat 
end program main 

我赞成第一种方法,它扩展好得多当你的计划和项目得到大模块化的好处开始成为必需品,而不是好的,但第二种方法适用于小型课程,而您正在学习语言。

+0

非常感谢您的回答。 –

+0

我喜欢将fortran 90(〜20年前)中介绍的功能称为“* modern *”:)。好的回答(+1) – mgilson