shell计算求和实例

2014-10-22

shell求和时候,可以利用$@参数或shift移位参数进行循环.

方法1:
[root@server100 opt]# more sum*
::::::::::::::
sum1
::::::::::::::
#!/bin/bash

if [[ -z $1 ]]||[[ -z $2 ]];then
echo "Usage: $0 sum1 sum2 ..."
exit 0;
fi

for x in $@;
do
sum=`expr $sum + $x`;
done
echo $sum

方法2:
::::::::::::::
sum2
::::::::::::::
#!/bin/bash
#shift move parameter to left
sum=0
while [ $# -gt 0 ]; do
((sum += $1))
shift;
done
echo "sum = $sum"

方法3:
::::::::::::::
sum3
::::::::::::::
#!/bin/sh

until (($#==0));
do
((sum+=$1));
shift
done
echo $sum

#!/bin/sh
if [ -z $1 ];then
echo Usage $0 num
exit 1
fi
x=$1
sum=0
until [[ x -eq 0 ]]; do
if [[ `expr $x % 2` -eq 1 ]];then
((sum=sum+x));
fi
((x--));
done
echo $sum

方法4: 指定n数值,求1+...+n和
[root@server100 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

方法5、
#!/bin/sh

echo $@|sed 's/ /+/g'|bc

分类:Linux | 标签: |

相关日志

评论被关闭!