0%

练习2-从1加到100

练习2-从1加到100

for循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@vm-101 ~]# cat lianxi1-100.sh
#!/bin/bash

# 注释说明,好习惯

for (( i=1; i<=100; i++))
do
sum=$[ $sum + $i ]
done

echo $sum

exit 0

[root@vm-101 ~]# bash lianxi1-100.sh
5050

while循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@vm-101 ~]# cat lianxi1-100.sh
#!/bin/bash

# 注释说明,好习惯

i=1
while [ $i -le 100 ]
do
sum=$[ $sum + $i ]
i=$[ $i + 1 ]
done

echo $sum

exit 0

[root@vm-101 ~]# bash lianxi1-100.sh
5050

在升级下

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
[root@vm-101 ~]# cat lianxi1-100.sh
#!/bin/bash

# 注释说明

read -p "输入起始数字:" i
read -p "输入结束数字:" end

while [ $i -le $end ]
do
sum=$[ $sum + $i ]
i=$[ $i + 1 ]
done

echo $sum

exit 0

[root@vm-101 ~]# bash lianxi1-100.sh
输入起始数字:10
输入结束数字:50
1230
[root@vm-101 ~]# bash lianxi1-100.sh
输入起始数字:1
输入结束数字:100
5050