在Ubuntu下使用Fortran进行输入输出操作,可以遵循以下步骤:
首先,确保你已经安装了Fortran编译器。常用的Fortran编译器有gfortran。你可以使用以下命令来安装它:
sudo apt update
sudo apt install gfortran
创建一个Fortran源文件,例如input_output.f90
,并编写你的程序。以下是一个简单的示例,展示了如何从标准输入读取数据并将其写入标准输出:
program input_output_example
implicit none
integer :: i
real :: x
! 提示用户输入
print *, "请输入一个整数:"
read *, i
print *, "请输入一个浮点数:"
read *, x
! 输出结果
print *, "你输入的整数是:", i
print *, "你输入的浮点数是:", x
end program input_output_example
使用gfortran编译你的Fortran程序:
gfortran -o input_output_example input_output.f90
这将生成一个可执行文件input_output_example
。
运行生成的可执行文件:
./input_output_example
程序将提示你输入一个整数和一个浮点数,然后输出你输入的值。
如果你需要进行文件输入输出操作,可以使用Fortran的文件I/O功能。以下是一个简单的示例,展示了如何从文件读取数据并将其写入另一个文件:
program file_io_example
implicit none
integer :: i, unit_number
real :: x
character(len=100) :: input_file_name, output_file_name
! 定义文件名
input_file_name = 'input.txt'
output_file_name = 'output.txt'
! 打开输入文件
open(unit=unit_number, file=input_file_name, status='old', action='read')
! 打开输出文件
open(unit=unit_number+1, file=output_file_name, status='replace', action='write')
! 读取和写入数据
do
read(unit_number, *, iostat=i) x
if (i /= 0) exit
write(unit_number+1, *) x
end do
! 关闭文件
close(unit_number)
close(unit_number+1)
print *, "文件操作完成。"
end program file_io_example
在这个示例中,程序从一个名为input.txt
的文件读取数据,并将数据写入一个名为output.txt
的文件。
使用gfortran编译并运行文件I/O程序:
gfortran -o file_io_example file_io_example.f90
./file_io_example
确保在当前目录下有一个名为input.txt
的文件,程序将读取该文件的内容并将其写入output.txt
。
通过这些步骤,你可以在Ubuntu下使用Fortran进行基本的输入输出操作,包括标准输入输出和文件输入输出。