怎么用linux-shell编写1到5的平方和

2024-12-04 15:44:50
推荐回答(4个)
回答1:

perl -e '$mul=1;foreach $i(1..5){$mul+=$i*$i;};print $mul,"\n";'

perl -e '$mul=1;foreach $i(6..10){$mul+=$i*$i;};print $mul,"\n";'

用perl果然太装x了么..

#!/bin/sh

m=`expr 1`
for i in `seq 1 5`
do
m=`expr $i \* $i + $m`
done
echo "From 1 to 5: $m"

set m=`expr 1`
for i in `seq 6 10`
do
m=`expr $i \* $i + $m`
done
echo "From 6 to 10: $m"

回答2:

#!/bin/sh

let i=1
let tot=0

# use -le is less or equal
while [ $i -le 5 ]
do
let tot=tot+(i*i)
#echo i=$i tot=$tot
let i=i+1
done
echo "total=$tot"

let tot=0
while [ $i -le 10 ]
do
let tot=tot+(i*i)
#echo i=$i tot=$tot
let i=i+1
done
echo "total=$tot"

exit 0

执行结果是:

total=55
total=330

回答3:

#!/bin/bash
fun()
{
for i in `seq $1 $2`
do
sum1=$(($i*$i))
sum2=$(($sum2+$sum1))
done
echo $sum2
}
echo "1^2+...+5^2=`fun 1 5`"
echo "6^2+...+10^2=`fun 6 10`"

回答4:

1楼果然装X 哈哈 玩笑 我是来zhuanfen的,不过你写的不错。