在Fortran中,往程序输入数据主要有以下几种方法:
通过命令行参数输入
使用`getarg`函数从命令行接收参数。例如:
```fortran
program get_command_line
implicit none
character(len=100) :: arg
integer :: i
! 检查是否有参数
call get_command_argument(1, arg)
print *, '参数是: ', trim(adjustl(arg))
end program get_command_line
```
运行程序时传递参数,如`./get_command_line hello`,程序会输出`参数是: hello`。
通过文件输入
使用`open`语句打开文件,并使用`read`语句从文件中读取数据。例如:
```fortran
program read_from_file
implicit none
integer :: i, j
real, allocatable, dimension(:,:) :: a
open(unit=8, file="a.txt")
read(8,*) i, j
allocate(a(i,j))
read(8,*) ((a(i,j), j=1,j), i=1,i)
close(8)
! 输出数组a
write(*,*) a
end program read_from_file
```
文件`a.txt`的内容格式为`m n`,接着是`m*n`个数据,如`2 3` `8.2 8.9 7.6 4.5 7.7 9.3`,程序会读取这些数据并存储在数组`a`中。
通过标准输入输入
使用`read`语句从标准输入(通常是键盘)读取数据。例如:
```fortran
program read_from_keyboard
implicit none
integer :: i
print *, '请输入一个整数:'
read(*,*) i
print *, '你输入的整数是:', i
end program read_from_keyboard
```
运行程序后,输入一个整数,程序会输出你输入的整数。
这些方法可以满足大部分从外部输入数据的需求。根据具体场景选择合适的输入方式即可。