【问题标题】:Variables Multiplication for the factorial calculation阶乘计算的变量乘法
【发布时间】:2013-02-19 05:22:36
【问题描述】:

我正在编写一个脚本来计算给定数字的阶乘,但我在乘法方面遇到了一些问题。

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

【问题讨论】:

  • 它会给你什么错误?

标签: bash multiplication factorial


【解决方案1】:

主要问题是你从来没有初始化result(到1),所以这个:

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

等价于:

result=$(( * $input))

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

【讨论】:

  • 非常感谢各位!它就像一个魅力一样工作我初始化了结果:)
猜你喜欢
  • 2015-04-19
  • 2010-12-17
  • 2022-01-17
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多