变量乘法

Ura*_*ake 32 bash multiplication factorial

我正在编写一个脚本,为插入的数字提供阶乘,但我在乘法时遇到了一些问题.

注意:因子由下式给出: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
Run Code Online (Sandbox Code Playgroud)

它不断给我不同的乘法技术的各种错误:/

目前输出是:

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
Run Code Online (Sandbox Code Playgroud)

非常感谢,最诚挚的问候

rua*_*akh 55

主要问题是你永远不会初始化result(to 1),所以这个:

result=$(($result * $input))
Run Code Online (Sandbox Code Playgroud)

相当于:

result=$(( * $input))
Run Code Online (Sandbox Code Playgroud)

这不是有效的算术表达式.