shell编程找出固定数组中最大值及出现次数
时间: 2023-06-23 15:08:50 浏览: 50
可以使用一个 for 循环和一个 if 语句来实现。假设固定数组为 arr,可以先将第一个元素设为最大值,然后遍历数组,如果当前元素比最大值大,则将当前元素设为最大值,并将出现次数重置为 1;如果当前元素等于最大值,则将出现次数加 1。最后输出最大值和出现次数即可。
下面是示例代码:
```shell
#!/bin/bash
arr=(3 6 2 8 4 6 9 6 2 1)
max=${arr[0]}
count=1
for i in "${arr[@]}"
do
if [ "$i" -gt "$max" ]
then
max="$i"
count=1
elif [ "$i" -eq "$max" ]
then
count=$((count+1))
fi
done
echo "最大值为 $max,出现次数为 $count"
```
相关问题
shell中怎么查看数组的值
在shell中,可以使用`${数组名[下标]}`的形式来查看数组的值。下标从0开始,表示数组中的元素位置。以下是一个示例:
```shell
#!/bin/bash
# 定义一个数组
fruits=("apple" "banana" "orange")
# 查看数组中第一个元素的值
echo ${fruits[0]} # 输出: apple
# 查看数组中第二个元素的值
echo ${fruits[1]} # 输出: banana
# 查看数组中第三个元素的值
echo ${fruits[2]} # 输出: orange
```
通过`${数组名[下标]}`来访问数组中的元素。在上面的示例中,`${fruits[0]}`表示访问`fruits`数组中的第一个元素。
编写shell脚本实现从键盘输入5个数放到数组中,用for循环找出五个数中的最大值并输出
好的,可以参考以下的Shell脚本代码:
```bash
#!/bin/bash
# 定义一个数组
nums=()
# 从键盘读取五个数,并放到数组中
echo "Please enter five numbers:"
for ((i=0; i<5; i++))
do
read nums[i]
done
# 找出数组中的最大值
max=${nums[0]}
for ((i=1; i<5; i++))
do
if [ ${nums[i]} -gt $max ]
then
max=${nums[i]}
fi
done
# 输出最大值
echo "The maximum number is: $max"
```
这个脚本首先定义了一个空数组`nums`。然后,使用for循环从键盘读取五个数,并将它们存储在数组中。接下来,使用另一个for循环来查找数组中的最大值,并将其存储在变量`max`中。最后,输出`max`变量的值,即最大值。