我必须编写一个程序,允许用户输入任意数量的数字,并确定哪个数字最大,最小,总和是多少,以及所有数字的平均值进入。我是否被迫使用数组来做到这一点,或者有另一种方式吗?如果我必须使用一个数组,有人可以帮我解释一下我应该如何处理这个问题吗?谢谢在UNIX中的bash shell中编写程序
-1
A
回答
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?
相关问题
- 1. unix bash shell脚本写作
- 2. Bash shell程序
- 3. 编写运行cygwin bash并执行程序的shell脚本
- 4. 如何在UNIX中为C程序编写makefile
- 5. 如何在bash shell脚本中编写这种for循环?
- 6. 在Bash Shell中是否存在像Bash中的进程替换?
- 7. bash脚本编写shell命令
- 8. 在shell脚本中触发UNIX序列
- 9. 在Unix Shell脚本中排序输入
- 10. Unix - 在shell脚本中排序
- 11. 在bash/shell/unix中删除给定范围的文件
- 12. 在Windows中的gcc无法编译为Unix/Linux编写的C程序
- 13. 在bash shell脚本(在unix中)重新加载.profile?
- 14. Bash shell程序启动C程序
- 15. 报价在UNIX shell中
- 16. unix shell编程特殊变量
- 17. 在C中编写我自己的shell
- 18. 功能vs脚本 - Unix Bash编程
- 19. 需要编写一个程序来正确配置登录shell
- 20. unix shell中的数组?
- 21. shell脚本中的Unix substr?
- 22. 子进程中`shell = True`中的`shell`是否意味着`bash`?
- 23. 在Matlab中使用bash shell
- 24. 在Maemo中运行bash shell
- 25. Bash Shell的新应用程序
- 26. 使用unix shell运行简单程序
- 27. 如何在Python中编写shell
- 28. 在Python中编写一个shell?
- 29. Script Bash and History Unix
- 30. unix bash命令
一个更具描述性的主题也可以。 – mgarciaisaia 2013-04-29 22:33:12