如何添加几个平方的总和(bourne 脚本)
How to add the sum of several squares (bourne scripting)
我正在尝试编写一个脚本,将整数列表作为命令行参数,计算每个整数的平方,然后给出平方和。这是我目前所拥有的...
if [ $# = 0 ]
then
echo "Usage: [=10=] integer-list"
exit 1
fi
for list in "$@"
do
echo "The square of $list is: $(($list*$list))"
done
如您所见,我有一个简单的 for 循环来处理方块,我只是不确定如何获得这些方块的总和并将其回显到屏幕上。有什么建议吗?
只需将先前平方的总和添加到列表中项目的当前平方。
#!/bin/bash
if [ $# = 0 ]
then
echo "Usage: [=10=] integer-list"
exit 1
fi
SUM=0
for ITEM in "$@"
do
SUM=$(($SUM+$ITEM*$ITEM))
done
echo "Sum of squares is :" $SUM
在命令行上-
$: for n in 2 3 4
> do q=$((n*n))
> echo "square of $n is $q"
> s=$((s+q))
> done; echo "Sum of squares: $s"
square of 2 is 4
square of 3 is 9
square of 4 is 16
Sum of squares: 29
在脚本中,您可以只说
for n in "$@"
我正在尝试编写一个脚本,将整数列表作为命令行参数,计算每个整数的平方,然后给出平方和。这是我目前所拥有的...
if [ $# = 0 ]
then
echo "Usage: [=10=] integer-list"
exit 1
fi
for list in "$@"
do
echo "The square of $list is: $(($list*$list))"
done
如您所见,我有一个简单的 for 循环来处理方块,我只是不确定如何获得这些方块的总和并将其回显到屏幕上。有什么建议吗?
只需将先前平方的总和添加到列表中项目的当前平方。
#!/bin/bash
if [ $# = 0 ]
then
echo "Usage: [=10=] integer-list"
exit 1
fi
SUM=0
for ITEM in "$@"
do
SUM=$(($SUM+$ITEM*$ITEM))
done
echo "Sum of squares is :" $SUM
在命令行上-
$: for n in 2 3 4
> do q=$((n*n))
> echo "square of $n is $q"
> s=$((s+q))
> done; echo "Sum of squares: $s"
square of 2 is 4
square of 3 is 9
square of 4 is 16
Sum of squares: 29
在脚本中,您可以只说
for n in "$@"