linux中 for语句和while语句计算1-100的和

 

1、for语句

[root@centos7 test2]# cat test.sh
#!/bin/bash
sum=0
for i in `seq $1`
do
let sum+=$i
done
echo "the sum of 1-$1 is: $sum"
[root@centos7 test2]# bash test.sh 100
the sum of 1-100 is: 5050
[root@centos7 test2]# bash test.sh 5
the sum of 1-5 is: 15

 

2、while语句

[root@centos7 test2]# cat test.sh
#!/bin/bash
sum=0
a=1
while [ $a -le $1 ]
do
let sum+=$a
let a++
done
echo "the sum of 1-$1 is: $sum"
[root@centos7 test2]# bash test.sh 100
the sum of 1-100 is: 5050
[root@centos7 test2]# bash test.sh 3
the sum of 1-3 is: 6

 

linux中 for语句和while语句计算1-100的和

上一篇:Qt系列文章016-UDP通信


下一篇:Web前端学习第四天——————HTML篇.016元素浮动特点