本文介绍了函数结果中的访问元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此Fortran代码不正确?

Why this Fortran code is incorrect?

function foo(x)
real x
real, dimension(3) :: foo
foo = (/1, 2, 3/)
end

...以及在主程序中

... and in main program

print*, foo(x)(1)

为什么我们不能直接访问函数结果中的元素?

Why we cannot access element in function result directly?

推荐答案

在思考自己的问题时

Why we cannot access element in function result directly?

我建议您也在主程序中编写几行,例如

I suggest you also write lines, in your main program, such as

res = foo(x)     ! having taken care to declare res appropriately
print*, res(1)

并继续进行编码.按您尝试的方式对函数调用编制索引在语法上不正确.

and get on with your coding. It's just not syntactically-correct to index a function call the way you've tried.

所以您对原始问题的答案是,因为这是Fortran语法的定义方式,您可能会被提示回答为什么Fortran的语法是这样定义的?如果此过程以对Fortran(现在已有50多年的历史)设计根源的引用的形式给出了答案,则您仍将不得不修改您的代码以使其与Fortran的语法保持一致.要确保您的编译器不会说,您知道,您编写的内容要比我编程接受的语法要好,我现在将其编译...

So one answer to your original question is because that's the way Fortran's syntax is defined to which you might be prompted to respond why is Fortran's syntax defined that way ? Even if this process turns up an answer in the form of reference to the roots of the design of Fortran (now over 50 years old) you're still going to have to modify your code to align with Fortran's syntax. For sure your compiler isn't going to say you know, what you've written is better than the syntax I've been programmed to accept, I'll compile that up right now ...

这篇关于函数结果中的访问元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 18:36