Linux Shell编程 期末考试

1,输入n,输出n的阶乘。

#!bin/bash
read -p "please input n:" n
ans=1
for (( i=$n; i>1; i-- ))
do
    ans=$[ans*i];
done
echo $ans

2,输入n,输出n是否是素数。

#bin/bash
read -p "please input n:" n
for(( i=$[n-1]; i>1; i-- ))
do
    rem=$[ $n % $i ]
    if [ $rem -eq 0 ]
    then
        echo "$n 不是素数"
        exit
    fi
done
echo "$n 是素数"

3,输入字符串str,输出str是否是回文。

#bin/bash
read -p "please input str:" str
cv=`echo $str|rev`
if [ $str -eq $cv ]
then
    echo "yes"
else
    echo "no"
fi

4,输入n个数,求平均数。

#!bin/bash
read -p "please input n:" n
echo "input"
sum=0
for (( i=0;i<$n;i++ ))
do
    read m
    sum=$[ $sum + $m ]
done
echo $[ $sum / $n ]

5,打印三角形

#!bit/bash
read -p "please input n:" n
n=7
for (( i=1; i<=$n; i++ ))
do
    for (( j=$n - i ; j>0; j-- ))
    do
        echo -n " "
    done
    for (( j=2*i-1; j>0; j-- ))
    do
        echo -n "*"
    done
    echo ""
done

6,斐波那契前n项和

#!/bin/bash
read -p "please input n:" n
a=1;
b=1;
c=2;
sum=4
for (( i=2;i<$n;i++ ))
do
    a=$b;
    b=$c;
    c=$[ $a + $b ]
    sum=$[ $sum + $c]
done
echo $sum

你可能感兴趣的:(Linux,Linux,Shell)