我真的不太了解数组,但我需要知道如何查找和打印数组的最大和最小值.该数组由读命令预定义,将提示用户输入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"
Run Code Online (Sandbox Code Playgroud)
总的想法是通过阵列一次迭代和跟踪什么max和min看到的迄今为止的每一步.
一些评论和解释在线(前缀#)
# 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"
Run Code Online (Sandbox Code Playgroud)
如果你需要比较(签名或不签名)INTegers,请尝试这样做:
#!/bin/bash
arr=( -10 1 2 3 4 5 )
min=0 max=0
for i in ${arr[@]}; do
(( $i > max || max == 0)) && max=$i
(( $i < min || min == 0)) && min=$i
done
echo "min=$min
max=$max"
Run Code Online (Sandbox Code Playgroud)
OUTPUT
min=-10
max=5
Run Code Online (Sandbox Code Playgroud)
说明
arr=( ) 是数组的声明((...))是一个算术命令,如果表达式非零,则返回退出状态0;如果表达式为零,则返回1.如果需要副作用(赋值),也用作"let"的同义词.请参见http://mywiki.wooledge.org/ArithmeticExpression[[是一个类似于(但比[命令更强大)的bash关键字.请参阅http://mywiki.wooledge.org/BashFAQ/031和http://mywiki.wooledge.org/BashGuide/TestsAndConditionals除非您正在为POSIX sh编写,我们建议[[foo || bar 当foo失败时运行bar: [[ -d $foo ]] || { echo 'ohNoes!' >&2; exit 1; }cmd1 && cmd2:执行cmd1,然后如果退出状态为0(true),则执行cmd2.请参阅http://mywiki.wooledge.org/BashGuide/TestsAndConditionals