2013-03-04 87 views
22

我正在做一個腳本,它給出了一個插入數字的階乘,但我在乘法中遇到了一些問題。變量乘法

注:階乘對於由下式給出: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 

它保持給我各種錯誤的diferent乘法工藝:/

目前的輸出是:

[email protected] ~/Á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 

非常感謝, 個問候

+1

它給你什麼錯誤? – iamnotmaynard 2013-03-04 23:31:24

回答

42

的主要問題是,你永遠不會初始化result(以1),所以這樣的:

result=$(($result * $input)) 

是相同的:

result=$((* $input)) 

這不是一個有效的算術表達式。

+0

許多謝謝你們!它工作就像一個魅力我初始化結果:) – UraniumSnake 2013-03-04 23:39:40

+0

@UraniumSnake:不客氣!我很高興聽到它。 :-) – ruakh 2013-03-04 23:49:00