阶乘计算中的变量乘法 [英] Variables Multiplication for the factorial calculation
本文介绍了阶乘计算中的变量乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个脚本来计算给定数字的阶乘,但我在乘法方面遇到了一些问题。
注意:的阶乘为:9!=9*8*7*6*5*4*3*2*1
以下是我的代码:
#!/bin/bash
echo "Insert an Integer"
read input
if ! [[ "$input" =~ ^[0-9]+$ ]] ; then
exec >&2; echo "Error: You didn't enter an integer"; exit 1
fi
function factorial
{
while [ "$input" != 1 ];
do
result=$(($result * $input))
input=$(($input-1))
done
}
factorial
echo "The Factorial of " $input "is" $result
对于不同的乘法技术,它一直给我各种错误:/
当前输出为:
joaomartinsrei@joaomartinsrei ~/Área de Trabalho/Shell $ ./factorial.sh Insert an Integer 3 ./factorial.sh: line 15: * 3: syntax error: operand expected (error token is "* 3") The factorial of 3 is
推荐答案
主要问题是您从未将result
(初始化为1
)初始化,因此:
result=$(($result * $input))
相当于:
result=$(( * $input))
这不是有效的算术表达式。
这篇关于阶乘计算中的变量乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文