用Fortran语言编写程序:、编写子程序,该程序可返回数组的中值。已知两个整型数组 a=[1 3 5 7 6 8 2 0], b=[1 3 5 7 6 8 2 0 11 15 20 25 19],请编写主程序,并调用子程序分别计 算两个数组的中值;并分别计算平均值,以及标准差。
时间: 2024-02-27 13:53:10 浏览: 226
FORTRAN程序设计第七章(数组的运算).ppt
以下是用Fortran语言编写的程序,包括主程序和子程序:
```
program main
integer :: a(8) = [1, 3, 5, 7, 6, 8, 2, 0]
integer :: b(13) = [1, 3, 5, 7, 6, 8, 2, 0, 11, 15, 20, 25, 19]
real :: median_a, median_b, avg_a, avg_b, std_a, std_b
median_a = median(a, 8)
median_b = median(b, 13)
avg_a = average(a, 8)
avg_b = average(b, 13)
std_a = stddev(a, 8)
std_b = stddev(b, 13)
write(*,*) 'The median of array a is:', median_a
write(*,*) 'The median of array b is:', median_b
write(*,*) 'The average of array a is:', avg_a
write(*,*) 'The average of array b is:', avg_b
write(*,*) 'The standard deviation of array a is:', std_a
write(*,*) 'The standard deviation of array b is:', std_b
end program main
real function median(arr, n)
integer, intent(in) :: arr(n)
integer :: n
integer :: i, j, k
integer :: tmp(n)
real :: median
tmp = arr
do i = 1, n-1
do j = i+1, n
if (tmp(j) < tmp(i)) then
k = tmp(i)
tmp(i) = tmp(j)
tmp(j) = k
end if
end do
end do
if (mod(n, 2) == 0) then
median = real(tmp(n/2) + tmp(n/2+1)) / 2.0
else
median = real(tmp(n/2+1))
end if
end function median
real function average(arr, n)
integer, intent(in) :: arr(n)
integer :: n
integer :: i
real :: sum, avg
sum = 0.0
do i = 1, n
sum = sum + real(arr(i))
end do
avg = sum / real(n)
end function average
real function stddev(arr, n)
integer, intent(in) :: arr(n)
integer :: n
integer :: i
real :: sum, avg, std
avg = average(arr, n)
sum = 0.0
do i = 1, n
sum = sum + (real(arr(i)) - avg)**2
end do
std = sqrt(sum / real(n))
end function stddev
```
编译运行后,程序将输出数组a和b的中值、平均值和标准差。注意,median函数返回的是实数类型,而不是整数类型。
阅读全文