2013-04-29 36 views
-1

我必须编写一个程序,允许用户输入任意数量的数字,并确定哪个数字最大,最小,总和是多少,以及所有数字的平均值进入。我是否被迫使用数组来做到这一点,或者有另一种方式吗?如果我必须使用一个数组,有人可以帮我解释一下我应该如何处理这个问题吗?谢谢在UNIX中的bash shell中编写程序

+0

一个更具描述性的主题也可以。 – mgarciaisaia 2013-04-29 22:33:12

回答

0

你不需要一个数组。只保留迄今为止最大和最小的数字,数字和总数。平均值只是sum/count

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

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,这是一个更大的外壳也进行测试。另请注意,这只适用于整数,平均值被截断(不是舍入)。

对于浮点,可以使用bc。使用

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嵌入它:但不是多次下探到不同的解释,为什么不把它写在一些更适合的问题,如蟒蛇Python或Perl中,如一个这里的文档,看到这个问题:How to pipe a here-document through a command and capture the result into a variable?

+0

谢谢这是一个巨大的帮助! – Drubs1181 2013-04-30 01:31:41

+0

所以给我一个投票或什么:-) – izak 2013-04-30 06:31:18

+0

对不起,我的代表太低,投票只是尚未。再次感谢,当我可以投票,我会def回来! – Drubs1181 2015-04-26 17:33:56