Variables Multiplication

久未见 提交于 2019-12-06 16:34:25

问题


I'm making a script which gives the factorial for a inserted number, but i'm having some problems with the multiplication.

Note: the factorial for is given by: 9!=9*8*7*6*5*4*3*2*1

Here's my code:

#!/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

it keeps giving me errors of all kinds for diferent multiplication technics :/

Currently the Output is:

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

Many Thanks, Best Regards


回答1:


The main problem is that you never initialize result (to 1), so this:

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

is equivalent to this:

result=$(( * $input))

which is not a valid arithmetic expression.



来源:https://stackoverflow.com/questions/15213127/variables-multiplication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!