在UNIX中用bash shell编写程序

时间:2013-04-29 22:02:23

标签: arrays bash unix for-loop

我必须编写一个程序,让用户输入他想要的数量,并确定哪个是最大的,最小的,总和是什么,以及输入的所有数字的平均值。我是否被迫使用数组来执行此操作,还是有其他方法?如果我必须使用数组,有人可以帮我解决一下我应该如何处理这个问题的例子吗?感谢

2 个答案:

答案 0 :(得分:0)

您不需要数组。只保留到目前为止最大和最小的数字,数字的数量和总和。平均值只是sum/count

要阅读输入,您可以在read循环中使用while

答案 1 :(得分:0)

简单的直接尝试,有一些问题:

#!/bin/bash

echo "Enter some numbers separated by spaces"
read numbers

# Initialise min and max with first number in sequence
for i in $numbers; do
    min=$i
    max=$i
    break
done

total=0
count=0
for i in $numbers; do
    total=$((total+i))
    count=$((count+1))
    if test $i -lt $min; then min=$i; fi
    if test $i -gt $max; then max=$i; fi
done
echo "Total: $total"
echo "Avg:   $((total/count))"
echo "Min:   $min"
echo "Max:   $max"

还使用/ bin / sh进行了测试,因此您实际上并不需要bash,这是一个更大的shell。另请注意,这仅适用于整数,并且平均值被截断(不是舍入的)。

对于浮点数,您可以使用bc。但是,为什么不把它写成更适合问题的东西,例如python或perl,而不是多次放入不同的解释器,例如在python中:

import sys
from functools import partial

sum = partial(reduce, lambda x, y: x+y)
avg = lambda l: sum(l)/len(l)

numbers = sys.stdin.readline()
numbers = [float(x) for x in numbers.split()]

print "Sum: " + str(sum(numbers))
print "Avg: " + str(avg(numbers))
print "Min: " + str(min(numbers))
print "Max: " + str(max(numbers))

您可以使用此处的文档将其嵌入bash中,请参阅此问题:How to pipe a here-document through a command and capture the result into a variable?

相关问题