#This function is used to generate random number between (0-100)
function RandomGen {
for i in {0..4}; do
arr[i]=$[$RANDOM%100]
echo Random Number $[$i+1] is ${arr[i]}
done
}
#This function is used to identify and display Highest and lowest number among generated random number.
function HighLow {
max=0 # ${arr[0]}
min=1000 # ${arr[0]}
for i in {1..4}; do
if [[ "${arr[i]}" -gt "$max" ]]; then
let "max = arr[i]"
fi
if [[ "${arr[i]}" -lt "$min" ]]; then
let "min = arr[i]"
fi
done
echo "Highest and lowest number among those random numbers are: $max and $min respectively."
}
答案1
简短回答:因为一开始,max
是可能的最小数字,并且min
高于可能的最大数字。
这是一个简单的算法,用于查找数组中的低点和高点。因为只有 4 次迭代,所以您应该能够将其写在纸上以查看发生了什么。或者,您可以在循环中放置大量回声以查看发生了什么。例如:
max=0 # ${arr[0]}
min=1000 # ${arr[0]}
for i in {1..4}; do
echo "Iteration $i: min=$min, max=$max"
if [[ "${arr[i]}" -gt "$max" ]]; then
echo "Found that ${arr[$i]} > $max"
let "max = arr[i]"
fi
if [[ "${arr[i]}" -lt "$min" ]]; then
echo "Found that ${arr[$i]} <$min"
let "min = arr[i]"
fi
done
echo "Highest and lowest number among those random numbers are: $max and $min respectively."
这会给你
Random Number 1 is 23
Random Number 2 is 19
Random Number 3 is 92
Random Number 4 is 42
Random Number 5 is 12
Iteration 1: min=1000, max=0
Found that 19 > 0
Found that 19 <1000
Iteration 2: min=19, max=19
Found that 92 > 19
Iteration 3: min=19, max=92
Iteration 4: min=19, max=92
Found that 12 <19
Highest and lowest number among those random numbers are: 92 and 12 respectively.
max
如果你一开始就给分配了 1000 ,就会出现问题。
- - 编辑 -
i=0
我错过了您填写 from to4
并循环到 i=1
to 的事实4
。
如果你循环0
到4
,我的答案仍然是正确的。
但是,否则,您的循环将仅检查arr[1]
to arr[4]
。如果最小值和最大值在数组的这一部分中,则答案将是正确的。但是,如果arr[0]
是最小值或最大值,则根据您的固定值min
和max
值,arr[0]
将不会被检查,并且您将错过最小值或最大值。
在我的示例中,arr[0]
为 23,大于最小值 19,因此答案是正确的。