bash - 如何生成和总结一个序列
问题描述
基本上,我想了解的是如何将之前已经声明的变量重新分配给新值。
我想在循环中将变量重新分配给不同的值。然后打印那个总和。
例如在 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。
解决方案
在这个答案中,我将您的变量名称更改为小写。这是 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"
推荐阅读
- c++ - 在头类中创建内联函数到私有变量
- java - 保存后休眠未设置自动生成的ID
- spring-data - 由于 ReadTimeoutException 调整 ReactiveElasticsearchClient
- react-native - 创建低版本 react-native 时出错
- react-native - react-native-image-crop-picker 相机或文件未打开 onpress
- c# - 如何将 int 写入 System.Span,即 int.Parse(span) 的反转?
- reactjs - 如何使用反应测试库测试带有钩子的反应组件
- c# - 如何使用 LINQ 使用泛型类型查询 [key] 属性?
- php - 为什么找不到我的 php 页面?我的 yaml 文件有问题吗?
- angular - 如何在角度类型js中隐藏图表linechartoption