阶乘方法导致错误 [英] factorial method resulting in error

查看:57
本文介绍了阶乘方法导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取数字 66 的阶乘值,但是我的方法导致输出 0 .但是,每当我尝试获取阶乘 5 时,它都会向我输出 120 .谁能告诉我为什么?

 public static int factorial(int n)
 {
            if (n == 1)
                return n;
            return n * factorial(n - 1);
 }

解决方案

当然-阶乘变得非常大,非常快.您正在迅速溢出int 非常的边界...在某些时候,您将乘以足够多的因子以使溢出变为0,这将使该值永远保持为0. /p>

根据Google的快速搜索,阶乘为66为5.44344939×10 92 -远远超过了int甚至是longdecimal的处理能力.您可能会得到double来处理它-您将损失大量的精度,这也会非常迅速地积累,但至少不会溢出...

I'm trying to get the factorial value of number 66, but my method resulting me an output 0. But whenever I try to get the factorial of 5, it is resulting me an output 120. Could anyone please tell me why?

 public static int factorial(int n)
 {
            if (n == 1)
                return n;
            return n * factorial(n - 1);
 }

解决方案

Sure - factorials get very big, very fast. You're overflowing the bounds of int very quickly... and at some point you'll have multiplied by enough factors to get an overflow to 0, which will then keep the value at 0 forever.

According to a quick Google search, 66 factorial is 5.44344939 × 1092 - which is considerably more than int can handle, or even long or decimal. You could get double to handle it - you'd lose a huge amount of precision, and that would accumulate really quickly too, but at least it wouldn't overflow...

这篇关于阶乘方法导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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