温馨提示×

ubuntufortran怎样处理数组

小樊
49
2026-10-21 18:54:24
栏目: 智能运维

在 Ubuntu 下使用 Fortran 处理数组,通常包含**安装编译器、声明数组、赋值、运算、输入输出、动态数组(可分配数组)**等内容。下面按实用方式说明(以 gfortran 为例)。


一、Ubuntu 下准备 Fortran 环境

sudo apt update
sudo apt install gfortran

测试:

gfortran --version

二、Fortran 数组基本用法

1. 静态数组(固定大小)

program array_demo
    implicit none
    integer :: a(5)
    integer :: i

    do i = 1, 5
        a(i) = i * 2
    end do

    print *, a
end program array_demo

编译运行:

gfortran array_demo.f90 -o array_demo
./array_demo

2. 数组下标范围自定义

real :: b(-2:2)

表示 b(-2), b(-1), b(0), b(1), b(2)


3. 二维数组

real :: mat(3,3)
integer :: i, j

do i = 1, 3
    do j = 1, 3
        mat(i,j) = real(i+j)
    end do
end do

print *, mat

三、数组整体操作(Fortran 强项)

1. 向量化运算(无需循环)

a = a + 1
b = sin(a)
c = a * b

2. 数组片段(切片)

print *, a(2:4)
a(1:3) = 0

四、动态数组(allocatable)

1. 一维动态数组

program dyn_array
    implicit none
    integer, allocatable :: x(:)
    integer :: n, i

    print *, "输入数组大小:"
    read *, n

    allocate(x(n))

    do i = 1, n
        x(i) = i
    end do

    print *, x

    deallocate(x)
end program dyn_array

2. 二维动态数组

real, allocatable :: m(:,:)
allocate(m(3,4))
m = 0.0
deallocate(m)

五、数组常用内置函数

函数 作用
size(a) 数组元素个数
shape(a) 各维大小
sum(a) 求和
maxval(a) 最大值
minval(a) 最小值
dot_product(a,b) 点积
matmul(a,b) 矩阵乘

示例:

print *, sum(a)
print *, maxval(a)

六、从文件读写数组

写数组到文件

open(10, file='data.txt')
write(10, *) a
close(10)

从文件读数组

open(10, file='data.txt')
read(10, *) a
close(10)

七、常见错误提醒

  1. 未写 implicit none(容易变量类型混乱)
  2. 动态数组未 allocate
  3. 数组越界(编译加 -fcheck=all)
gfortran -fcheck=all program.f90

八、简单示例(综合)

program main
    implicit none
    integer, allocatable :: v(:)
    integer :: n, i

    n = 5
    allocate(v(n))
    v = [(i, i=1,n)]

    print *, "原数组:", v
    print *, "和:", sum(v)
    v = v * 2
    print *, "乘2后:", v

    deallocate(v)
end program main

如果你有具体需求(如数值计算、矩阵运算、和 C/Python 交互、MPI 并行数组等),可以告诉我,我可以给你更针对性的示例。

0 踩