jiechen=1 #申明变量
for bb in `seq 1 3` #计算1到3的阶乘
do
jiechen=`expr ${bb} \* ${jiechen}` #循环结算
done
echo "10! = ${jiechen}" #打印结果
#!/bin/bashecho "请输入整数M、N(M>N)"
echo "M:"
read M
#判断M是否非空且为整数
if [ -z $M ]
then
echo "M 必须非空"
exit 1
elif ! [[ $M =~ ^-?[0-9]*$ ]]
then
echo "M 必须为整数"
exit 1
fi
echo "N:"
read N
#判断N是否非空且小于N的整数
if [ -z $N ]
then
echo "N 必须非空"
exit 1
elif ! [[ $N =~ ^-?[0-9]*$ ]]
then
echo "N 必须为整数"
exit 1
elif [ $M -le $N ]
then
echo "N必须小于M"
exit 1
fi
let "base = M-N"
result=1
#阶乘函数,引入result实现运算的线性增长
fac (){
base=$1
result=$2
if [ $base -gt 0 ]
then
let "result *= base"
let "base -= 1"
fac $base $result
fi
}
#计算阶乘
fac $base $result
echo "M-N的阶乘为$result"
exit 0
上次看错题目了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)