利用Fortran计算任意十个数的平均值和标准差
时间: 2023-11-22 07:55:07 浏览: 213
以下是利用Fortran计算任意十个数的平均值和标准差的代码:
```
program average_std
implicit none
real :: num(10) ! 存储十个数字
real :: avg, std ! 平均值和标准差
real :: sum, sum_sq ! 总和和平方和
integer :: i ! 循环计数器
! 读入十个数字
do i = 1, 10
write(*,*) '请输入第', i, '个数字:'
read(*,*) num(i)
end do
! 计算平均值
sum = 0.0
do i = 1, 10
sum = sum + num(i)
end do
avg = sum / 10.0
! 计算标准差
sum_sq = 0.0
do i = 1, 10
sum_sq = sum_sq + (num(i) - avg)**2
end do
std = sqrt(sum_sq / 10.0)
! 输出结果
write(*,*) '平均值为:', avg
write(*,*) '标准差为:', std
end program average_std
```
在上面的代码中,首先定义了一个包含10个实数的数组 `num`,用来存储输入的数字。然后通过循环读入这10个数字,并计算它们的总和。接着计算平均值和标准差,最后输出结果。其中,计算标准差时使用了 `sqrt` 函数来计算平方根。
相关问题
利用Fortran统计输入的10个数据中数组元素的下标与其值相同的元素个数
下面是一个简单的Fortran程序,可以计算输入的10个数据中数组元素的下标与其值相同的元素个数:
```
program count_same_index_value
implicit none
integer :: i, count, values(10)
! Read in values
print *, "Enter 10 integer values:"
do i = 1, 10
read *, values(i)
end do
! Count values with same index and value
count = 0
do i = 1, 10
if (i == values(i)) then
count = count + 1
end if
end do
! Output results
print *, "The number of elements with the same index and value is:", count
end program count_same_index_value
```
在这个程序中,我们首先定义了一个整数数组 `values`,并要求用户输入10个整数。然后我们遍历这个数组,如果当前元素的下标等于它的值,则将计数器 `count` 加 1。最后输出计数器的值作为结果。
利用Fortran求一组数中的最大值最小值及其下标
以下是利用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
```
在这个示例程序中,我们首先读取用户输入的数组大小和数组元素,然后使用一个循环遍历数组中的所有元素,同时更新最大值、最小值及其对应的下标。最终输出求得的最大值、最小值及其下标。