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
复制代码

 

posted @   小鲨鱼2018  阅读(3962)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示