为什么我的 bash 函数返回错误的值? [英] Why does my bash function return the wrong value?

查看:42
本文介绍了为什么我的 bash 函数返回错误的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fact() 
{
    if [ $1 -eq 1 ]
    then
        return 1
    else
        y=`expr $1 - 1`
        fact $y
        b=$(($1 * $?))
        return $b
    fi
}
echo "enter"
read n
fact $n
echo "$?"

这是一个求一个数的阶乘的程序.输出正确到 5.6 的输出是 208,但正确答案是 720.是什么导致了这个错误?

This is a program to find the factorial of a number. The output is correct up to 5. The output of 6 is giving as 208 but the correct answer is 720. What's causing this error?

推荐答案

函数返回值最多只能到255:

Function return values can only go up to 255:

a()
{
        return 255
}

a
echo $?

b()
{
        return 256
}

b
echo $?

产生:

$ bash x.sh
255
0

return 就像 exitexit 最多只能取 255 的值(http://www.unix.org/whitepapers/shdiffs.html).

return is like exit and exit can only take values up to 255 (http://www.unix.org/whitepapers/shdiffs.html).

另一种选择是切换到迭代建议,如另一个答案中所述.或者,您可以使用 echo 并以这种方式捕获递归输出:

One alternative is to switch to an iterative suggestion, as described in another answer. Alternatively you can use echo and capture the recursive output that way:

#!/bin/bash

fact() 
{
    if [ $1 -eq 1 ]
    then
        echo 1
    else
        y=$(expr $1 - 1)
        f=$(fact $y)
        b=$(($1 * $f))
        echo $b
    fi
}
echo "enter"
read n
fact $n

这篇关于为什么我的 bash 函数返回错误的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆