加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 变量乘法

发布时间:2020-12-15 19:11:48 所属栏目:安全 来源:网络整理
导读:我正在制作一个脚本,为插入的数字提供阶乘,但是我有一些乘法问题。 注意:因子由下式给出:9!= 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 这是我的代码: #!/bin/bashecho "Insert an Integer"read inputif ! [[ "$input" =~ ^[0-9]+$ ]] ; then exec 2; echo "
我正在制作一个脚本,为插入的数字提供阶乘,但是我有一些乘法问题。

注意:因子由下式给出: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

它不断给我不同的乘法技术的错误:/

目前的输出是:

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

非常感谢,
最好的祝福

主要的问题是你永远不会初始化结果(1),所以这样:
result=$(($result * $input))

相当于:

result=$(( * $input))

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读