编写一个shell程序,实现求sum=1-1/2+1/3-1/4......-1/20

如题所述

[root@localhost ~]# cat dd
sum=1
i=2
while [ $i -lt 21 ]
do
if [ `expr $i % 2` -eq 0 ];then
sum=`echo "$sum - 1/$i"|bc -l`
else
sum=`echo "$sum + 1/$i"|bc -l`
fi
i=`expr $i + 1`
done
echo $sum
[root@localhost ~]# sh dd
.66877140317542794322
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-06-08
perl -e '$s -= (-1)**$_/$_ for 1..20;print $s'
相似回答