要求:编写一个脚本,该脚本提示用户输入一些整数,然后通过程序控制分别计算出这些整数中的奇数之和与偶数之和,并输出。
我的思路是结合数组来实现:
#!/bin/bash #charpter_8-9 #trap 'echo "Before executing the line: $LINENO,sum2=$sum2,sum1=$sum1"' DEBUG declare -a array1 echo "Please input some integer numbers separated by SPACE:" read -a array1 echo The length of array1 is: "${#array1[@]}" let max="${#array1[@]}" let sum_odd=0 let sum_even=0 fun() { 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-9 Please input some integer numbers separated by SPACE: 12 23 34 45 56 67 78 The length of array1 is: 7 奇数之和:sum_odd=135 偶数之和:sum_even=180 #测试二 [root@localhost charpter8]# sh 8-9 Please input some integer numbers separated by SPACE: 11 12 21 22 32 33 The length of array1 is: 6 奇数之和:sum_odd=65 偶数之和:sum_even=66
可以看到,脚本可以正常获取想要的结果。