利用Fortran求一组数中的最大值最小值及其下标
时间: 2023-11-22 18:55:18 浏览: 294
以下是利用Fortran求一组数中的最大值最小值及其下标的示例代码:
```
program find_max_min_index
implicit none
integer :: n,i,max_index,min_index
real :: a(100),max_val,min_val
write(*,*) "Enter the number of elements in the array: "
read(*,*) n
write(*,*) "Enter the elements of the array: "
do i = 1, n
read(*,*) a(i)
end do
! Initialize max and min values with the first element
max_val = a(1)
min_val = a(1)
max_index = 1
min_index = 1
! Loop over the remaining elements of the array
do i = 2, n
if (a(i) > max_val) then
max_val = a(i)
max_index = i
end if
if (a(i) < min_val) then
min_val = a(i)
min_index = i
end if
end do
write(*,*) "Maximum value: ", max_val
write(*,*) "Index of maximum value: ", max_index
write(*,*) "Minimum value: ", min_val
write(*,*) "Index of minimum value: ", min_index
end program find_max_min_index
```
在这个示例程序中,我们首先读取用户输入的数组大小和数组元素,然后使用一个循环遍历数组中的所有元素,同时更新最大值、最小值及其对应的下标。最终输出求得的最大值、最小值及其下标。
阅读全文