bash 变量乘法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15213127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:25:04  来源:igfitidea点击:

Variables Multiplication

bashmultiplicationfactorial

提问by UraniumSnake

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

注意:阶乘为: 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

非常感谢,最好的问候

回答by ruakh

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

主要问题是您从未初始化result(to 1),因此:

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

is equivalent to this:

相当于:

result=$(( * $input))

which is not a valid arithmetic expression.

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