在Linux下用shell高斯求和怎么写?

在Linux下用shell高斯求和,求告知怎么写。
阅读 4.5k
3 个回答
#!/bin/bash
read -p "Input value of n: " n
sum=0
i=1
while (($i<=$n))
do
sum=$(($sum +$i))
i=$(($i+1))
done
echo "SUM is $sum."
#/usr/bin/sh

n=$1
sum=0

# 方法1  循环
for i in $(seq 1 $n); do
    ((sum = $sum + $i))
done
echo $sum

# 方法2  公式
((sum=(1 + $n) * $n / 2))
echo $sum

数列和sum=(首项h+末项t)×项数i÷2
项数n=(末项t-首项h)÷公差s+1
公差s=数列中两个数字之间的步进距离

#!/bin/bash
read -p "Input the head number: " h
read -p "Input the tail number: " t
read -p "Input the step length: " s
sum=(h+t)*((t-h)/s+1)/2

如23456求和
首项h=2
尾项t=6
公差s=1
sum=(2+6)((6-2)/1+1)/2
=8*(4+1)/2
=8*5/2
=20

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进