本文共 997 字,大约阅读时间需要 3 分钟。
要求:编写一个脚本,该脚本提示用户输入一些整数,然后通过程序控制分别计算出这些整数中的
奇数之和与偶数之和,并输出。
我的思路是结合数组来实现:
#!/bin/bash#charpter_8-9#trap 'echo "Before executing the line: $LINENO,sum2=$sum2,sum1=$sum1"' DEBUGdeclare -a array1echo "Please input some integer numbers separated by SPACE:"read -a array1echo The length of array1 is: "${#array1[@]}"let max="${#array1[@]}"let sum_odd=0let sum_even=0fun(){ for ((i=0;i<$max;i++)) do let "temp=array1[i]%2" if [ "$temp" -eq "0" ] then let sum_even+=array1[i] else let sum_odd+=array1[i] fi done echo "奇数之和:sum_odd=$sum_odd" echo "偶数之和:sum_even=$sum_even"}fun
执行测试:
#测试一[root@localhost charpter8]# sh 8-9Please input some integer numbers separated by SPACE:12 23 34 45 56 67 78The length of array1 is: 7奇数之和:sum_odd=135偶数之和:sum_even=180#测试二[root@localhost charpter8]# sh 8-9Please input some integer numbers separated by SPACE:11 12 21 22 32 33The length of array1 is: 6奇数之和:sum_odd=65偶数之和:sum_even=66
可以看到,脚本可以正常获取想要的结果。
转载地址:http://cjhlo.baihongyu.com/