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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律