Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

bash - Variables Multiplication for the factorial calculation

I'm making a script that calculates the factorial for a given 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 different 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
question from:https://stackoverflow.com/questions/15213127/variables-multiplication-for-the-factorial-calculation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...