加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 在Linux shell脚本中如何打印数组的最大值和最小值?

发布时间:2020-12-15 22:27:39 所属栏目:安全 来源:网络整理
导读:我真的不太了解数组,但我需要知道如何查找和打印数组的最大和最小值.该数组由读命令预定义,将提示用户输入n个整数. 如何将读取输入分配给数组并查找并显示数组的最大值和最小值? 有没有办法测试数组元素,看看它们是否都是整数? #!/bin/bashread -a integer
我真的不太了解数组,但我需要知道如何查找和打印数组的最大和最小值.该数组由读命令预定义,将提示用户输入n个整数.

如何将读取输入分配给数组并查找并显示数组的最大值和最小值?

有没有办法测试数组元素,看看它们是否都是整数?

#!/bin/bash

read -a integers

biggest=${integers[0]}
smallest=${integers[0]}

for i in ${integers[@]}
do
     if [[ $i -gt $biggest ]]
     then
        biggest="$i"
     fi

     if [[ $i -lt $smallest ]]
     then
        smallest="$i"
     fi
done

echo "The largest number is $biggest"
echo "The smallest number is $smallest"

解决方法

一般的想法是迭代数组一次,并跟踪到目前为止在每一步看到的最大值和最小值.

一些注释和解释在线(以#为前缀)

# This is how to declare / initialize an array:
arrayName=(1 2 3 4 5 6 7)

# Use choose first element of array as initial values for min/max;
# (Defensive programming) - this is a language-agnostic 'gotcha' when
# finding min/max ;)
max=${arrayName[0]}
min=${arrayName[0]}

# Loop through all elements in the array
for i in "${arrayName[@]}"
do
    # Update max if applicable
    if [[ "$i" -gt "$max" ]]; then
        max="$i"
    fi

    # Update min if applicable
    if [[ "$i" -lt "$min" ]]; then
        min="$i"
    fi
done

# Output results:
echo "Max is: $max"
echo "Min is: $min"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读