带有自定义数字的阶乘函数不起作用

factorial function with custom numbers doesn't work

最近我一直在开发一个库来处理具有数千位数字的非常大的数字。 我现在已经为这些东西研究了一个阶乘函数,因为我刚刚设置了乘法。

largeNum factorial(largeNum& input) {
    if (input > one) return (input * factorial(--input));
    else return one;
}

"one" 是一个 largeNum,定义为具有“+”符号的值"one",因为我还没有实现整数转换。

阶乘是 largeNum class 的友元函数。我没有得到任何语法错误,它必须是合乎逻辑的。

前缀 -- 运算符已正确重载并经过测试。

乘法和“>”运算符也是如此。

也许我只是瞎了眼,因为我有点睡眠不足,但我需要一些帮助。 干杯。

回答您的问题:"unexpected" 结果,即 "entering 5 gives 4!, not 5!",与以下代码行引入的未定义行为有关:

input * factorial(--input)

请注意,C++ 中运算符的求值顺序大部分是未定义的(例如,参见 cppreference). So it may happen that factorial(--input) is evaluated before it's result is multiplied by the (in the meanwhile changed?) value of input. In conjunction with side effects, where an operation alters the same (or an other) object, this usually results in undefined behaviour when the same (or the other) object is used in the same expression without having a sequence point in between. Just as operation n = ++i + i; is UB (cf. evaluation order / undefined behaviour)。

因此,这段代码有时可能会如您所愿,但也可能完全不同。

所以如果 --inputinput 的内容有副作用(正如我们假设的那样),那么您的代码必须重写为

input * factorial(input-one)

其中 (input - one) 不得以任何方式改变 input(当然,必须以给出正确结果的方式实施)。