2013-03-04 88 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