在Fortran中输出类似Markdown的表格
在Fortran中输出类似Markdown的表格可以通过格式化输出实现。以下是一些方法和示例:
基本方法
使用格式说明符
program markdown_table
implicit none
character(len=20) :: names(3)
real :: values(3)
integer :: i
! 数据
names = ['Apple', 'Banana', 'Orange']
values = [2.5, 1.8, 3.2]
! 输出表头
write(*,'(A20,A1,A10)') 'Fruit', '|', 'Price (€)'
write(*,'(A20,A1,A10)') '--------------------', '|', '----------'
! 输出数据行
do i = 1, 3
write(*,'(A20,A1,F10.2)') names(i), '|', values(i)
end do
end program markdown_table
使用循环和字符串操作
program advanced_table
implicit none
character(len=15), parameter :: fmt_header = '(A15,2("|",A15))'
character(len=15), parameter :: fmt_sep = '(15("-"),2("+",15("-")))'
character(len=15), parameter :: fmt_row = '(A15,2("|",F15.2))'
character(len=15) :: items(3) = ['Laptop', 'Phone', 'Tablet']
real :: prices(3) = [999.99, 699.50, 349.99]
integer :: stocks(3) = [25, 40, 15]
integer :: i
! 表头
write(*,fmt_header) 'Item', 'Price ($)', 'Stock'
write(*,fmt_sep)
! 数据行
do i = 1, 3
write(*,fmt_row) items(i), prices(i), real(stocks(i))
end do
end program advanced_table
更复杂的动态表格
module table_utils
implicit none
contains
subroutine print_table(header, data, widths)
character(len=*), intent(in) :: header(:)
real, intent(in) :: data(:,:)
integer, intent(in) :: widths(:)
integer :: i, j, ncols, nrows
character(len=100) :: fmt
ncols = size(header)
nrows = size(data, 1)
! 创建格式字符串
write(fmt, '("(",I0,"(A",I0,",1X))")') ncols, (widths(j), j=1,ncols)
! 打印表头
write(*,fmt) header
write(*,fmt) (repeat('-', widths(j)), j=1,ncols)
! 创建数据格式
write(fmt, '("(",I0,"(F",I0,".2,1X))")') ncols, (widths(j), j=1,ncols)
! 打印数据
do i = 1, nrows
write(*,fmt) (data(i,j), j=1,ncols)
end do
end subroutine print_table
end module table_utils
program test_table
use table_utils
implicit none
character(len=15) :: headers(3) = ['Temperature', 'Pressure', 'Humidity']
real :: measurements(4,3) = reshape( &
[25.4, 1013.2, 45.0, &
26.1, 1012.8, 43.5, &
24.9, 1013.5, 47.2, &
25.7, 1012.9, 46.1], [4,3])
integer :: col_widths(3) = [12, 10, 10]
call print_table(headers, measurements, col_widths)
end program test_table
输出到文件
program file_table
implicit none
integer, parameter :: n = 4
character(len=10) :: cities(n) = ['New York', 'London', 'Tokyo', 'Paris']
real :: temps(n) = [22.5, 18.3, 25.1, 20.7]
integer :: i, u
! 打开文件
open(newunit=u, file='weather.md', status='replace')
! 写入Markdown表格
write(u, '(A)') '| City | Temperature |'
write(u, '(A)') '|-----------|-------------|'
do i = 1, n
write(u, '(A,A,A,F6.1,A)') '| ', trim(cities(i)), ' | ', temps(i), ' |'
end do
! 关闭文件
close(u)
print *, 'Table written to weather.md'
end program file_table
这些示例展示了如何在Fortran中创建类似Markdown的表格输出。你可以根据需要调整格式说明符和布局来满足特定的表格需求。