shell编程连载【2】-+1~100求和

【方法1】运用for in语句

(1) bash

#! /bin/bash
sum=0;
for i in {1..100}
do
        ((sum = sum + i))
done

echo $sum

(2) perl

#! /usr/bin/perl
$sum=0;
for ($i = 0; $i <=100 ; $i+=1)
{
        $sum +=$i;
}
print "$sum\n";


【方法2】运用while语句

(1) bash

#! /bin/bash
i=0;
sum=0;
while [ "$i" -lt 100 ]
do
        ((i = i + 1))
        (( sum = sum + i))
done

echo $sum

(2) perl

#! /usr/bin/perl
$i=0;
$sum=0;
while($i<=100)
{
        $sum+=$i;
        $i+=1;
}
print "$sum\n";


【方法3】运用continue和break

#! /bin/bash
i=0;
sum=0;

while [ "$i" -lt 500 ]
do
if [ "$i" -lt 100 ]
then
        ((i = i + 1));
        (( sum = sum + i))
        continue;
else
        break;
fi
done

echo $sum


 

你可能感兴趣的:(编程,shell)