首页 > 系统服务 > 详细

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

时间:2021-04-22 15:21:52      阅读:38      评论:0      收藏:0      [点我收藏+]

 

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的和

原文:https://www.cnblogs.com/liujiaxin2018/p/14689109.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!