编写一个shell脚本,求累加和1+2+3……+100,输入s=5050;然后再运行该脚本,Lin

2024-11-07 12:57:19
推荐回答(4个)
回答1:

指定n数值,求1+…+n和
[root@server opt]# more n.sh
#!/bin/sh
sum=0
function ff_forsum(){
for num in $(seq $1)
do
sum=$(($sum+$num))
done
}
function ff_whilesum(){
i=1
while(($i<=$1))
do
sum=$(($sum+$i))
i=$(($i+1))
done
}
# call ff_forsum
ff_forsum $1
echo $sum
sum=0
# call ff_whilesum
ff_whilesum $1
echo $sum

回答2:

sum=0
for ((i=0;i<=100;i++))
do
sum=$(($sum+$i))
done
echo "s=$sum"

回答3:

#!/bin/bash

sum=0
for i in {1..100};do
let sum+=$i
done
echo "s="$sum

回答4:

#!/bin/bash
sum=0
i=1
while (($i<=100))
do
sum=$(($sum +$i))
i=$(($i+1))
done
echo "s=$sum"