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

 

[root@centos7 test2]# cat test.sh #!/bin/bash sum=0 read -p "please input an integer: " num if [[ $num =~ [^0-9] ]]; then echo "input error." exit 10 elif [ $num -eq 0 ]; then echo "input error." exit 20
else
for i in `seq 1 $num`; do sum=$[$sum+$i] done echo $sum fi unset sum [root@centos7 test2]# bash test.sh please input an integer: abcd input error. [root@centos7 test2]# bash test.sh please input an integer: 0 input error. [root@centos7 test2]# bash test.sh please input an integer: -3 input error. [root@centos7 test2]# bash test.sh please input an integer: 100
5050

 

1-100的和

[root@centos7 test2]# for ((i=1,sum=0; i<=100; i++)); do let sum+=$i; done [root@centos7 test2]# echo $sum 5050

 

1-100中偶数的和

[root@centos7 test2]# for ((i=1,sum=0; i<=100; i++)); do [[ $[i%2] -eq 0 ]] && sum=$[$sum+$i]; done [root@centos7 test2]# echo $sum 2550

 

1-100中奇数的和

[root@centos7 test2]# for ((i=1,sum=0; i<=100; i++)); do [[ $[i%2] -eq 1 ]] && let sum+=$i; done [root@centos7 test2]# echo $sum 2500

 

 

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

 

1-100内所有奇数的和

[root@centos7 test2]# cat test.sh #!/bin/bash i=1 sum=0
while [ $i -le 100 ]; do
if [ $[i%2] -ne 0 ]; then let sum+=$i let i++
else let i++ fi done echo $sum [root@centos7 test2]# bash test.sh 2500

 

1-100内所有偶数的和

[root@centos7 test2]# cat test.sh #!/bin/bash i=1 sum=0
while [ $i -le 100 ]; do
if [ $[i%2] -eq 0 ]; then sum=$[$sum+$i] let i++
else let i++ fi done echo $sum unset sum [root@centos7 test2]# bash test.sh 2550

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM