要求:使用while循环编写脚本,使其完成以下功能:
1.提示用户输入两个整数:firstNum和secondNum(firstNum的值一定要小于secondNum)
2.输出所有介于这两数之间的奇数
3.输出所有介于这两数目之间偶数之和
先看一下如何用for循环实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
#!/bin/bash #chapter_8-14 echo "Please input two integer numbers(the first must be smaller than the second):"
read firstNum secondNum
#定义函数fun0,判断输入的两个数的大小 fun0() { while [ $1 -lt $2 ]
do
echo "Your input:" "$firstNum " "$secondNum"
break
done
} fun0 $firstNum $secondNum #定义一个数组,将两个数之间的所有数写入数组 declare -a arr1
i=firstNum arr1=($( for ((i=firstNum;i<=secondNum;i++))
do echo -n "$i "
done )) length=${ #arr1[@]}
sum_even=0 if [[ "arr1[0]%2" - eq 0 ]]
then for ((j=0;j<=length;j=j+2))
do
let sum_even+=arr1[j]
echo -n "${arr1[j+1]} "
done
echo "偶数之和为:" $sum_even
else for ((k=0;k<=length;k=k+2))
do
let sum_even+=arr1[k+1]
echo -n "${arr1[k]} "
done
echo "偶数之和为:" "$sum_even "
fi |
脚本执行效果:
1
2
3
4
5
6
7
8
9
10
|
[root@localhost charpter8] # sh 8-14
Please input two integer numbers(the first must be smaller than the second): 3 29 Your input: 3 29 3 5 7 9 11 13 15 17 19 21 23 25 27 29 偶数之和为: 208 [root@localhost charpter8] # sh 8-14
Please input two integer numbers(the first must be smaller than the second): 8 29 Your input: 8 29 9 11 13 15 17 19 21 23 25 27 29 偶数之和为: 198 |
while 循环实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
#!/bin/bash echo "Pleas input two integer number(the first num must be smaller than the second one):"
read firstNum secondNum
fun0() { while [ $1 -lt $2 ]
do
echo "Your input is:" "$firstNum " "$secondNum"
break
done
} fun0 $firstNum $secondNum declare -a arr1
let i=firstNum
arr1=( $(
while ((i<=secondNum))
do
echo "$i "
let i++
done
)
) length=${ #arr1[@]}
j=0 k=0 sum_even=0 if [[ "arr1[0]%2" - eq 0 ]]
then while ((j<length))
do
echo -n "${arr1[j+1]} "
let sum_even+=arr1[j]
let j=j+2
done
echo "偶数之和:$sum_even"
else while ((k<length))
do
echo -n "${arr1[k]} "
let sum_even+=arr1[k+1]
let k=k+2
done
echo "偶数之和:$sum_even"
fi |
脚本执行效果:
1
2
3
4
5
6
7
8
9
10
|
root@localhost charpter8] # sh 8-14-1
Pleas input two integer number(the first num must be smaller than the second one): 31 38 Your input is: 31 38 31 33 35 37 偶数之和:140 [root@localhost charpter8] # sh 8-14-1
Pleas input two integer number(the first num must be smaller than the second one): 30 39 Your input is: 30 39 31 33 35 37 39 偶数之和:170 |
两种循环实现发现大致相似.
本文转自 marbury 51CTO博客,原文链接:http://blog.51cto.com/magic3/1429193