首页 > 解决方案 > 如何生成和总结一个序列

问题描述

基本上,我想了解的是如何将之前已经声明的变量重新分配给新值。

我想在循环中将变量重新分配给不同的值。然后打印那个总和。

例如在 JavaScript 中,

sum = 0;

for... (loop)
sum = sum + start-point; (loop body)

console.log(sum)

现在我似乎无法在 bash 中得到它。

这是我在 bash 中的代码

echo Enter a number:
read NUMBER
echo Enter a startpoint:
read STARTPOINT
echo Enter how many terms:
read TERMS
sum=0;
for ((n=0;n<$TERMS;n++));
do
   STARTPOINT=$((STARTPOINT + NUMBER))
   sum=$(($sum + $STARTPOINT))
        echo $STARTPOINT
        echo $sum
done

除总和部分外,所有代码都是正确的,因此代码无法正常运行。如果我删除那部分,它工作正常。我只需要将变量STARTPOINT的输出相加。

例子

输入

NUMBER = 3 (means to increment 3 in the startpoint)
STARTPOINT = 2
TERMS = 5 (means to add 3 to 2 five times)

预期产出

5
8
11
14
17

我遇到困难的部分是如何添加所有这些数字,当所有这些数字相加时,它应该打印 55。

标签: bashshell

解决方案


在这个答案中,我将您的变量名称更改为小写。这是 bash 中的常规命名方案,以避免与内置变量和环境变量发生意外名称冲突。

如果我理解正确,您想构建以下序列并对其进行总结:

startpoint + 1*number+ startpoint + 2*number+ ... +startpoint+ term*number

在这种情况下,您不应startpoint循环内进行更改。使用另一个变量来存储startpoint + n*number.

startpoint=2 number=3 terms=5 sum=0
echo "$terms times increment $startpoint by $number:"
for ((n=1; n<=terms; n++));
do
  ((addend = startpoint + n*number))
  echo "$addend"
  ((sum += addend))
done
echo "The sum is $sum"

但是,您可以使用打印序列而不是使用慢循环,然后使用三角数seq的封闭公式计算其总和:

startpoint=2 number=3 terms=5
seq $((startpoint+number)) $number $((startpoint+terms*number))
((sum = terms*startpoint + terms*(terms+1)/2 * number))
echo "The sum is $sum"

推荐阅读