阶乘函数对21产生错误的结果!以上 [英] Factorial function produces wrong result for 21! and above

查看:101
本文介绍了阶乘函数对21产生错误的结果!以上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for (int i = 0; i <= 25; i++)
    System.out.printf("%d! = %,d\n", i, factorial(i));

上面的代码初始化下面的阶乘方法:

The code above initializes the factorial method below:

public static long factorial(int num1)
{
    if (num1 == 0)
        return 1;
    else
        return Math.abs(num1 * factorial(num1 - 1));
}

因此,将创建以下输出:

As so the following output is created:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5,040
8! = 40,320
9! = 362,880
10! = 3,628,800
11! = 39,916,800
12! = 479,001,600
13! = 6,227,020,800
14! = 87,178,291,200
15! = 1,307,674,368,000
16! = 20,922,789,888,000
17! = 355,687,428,096,000
18! = 6,402,373,705,728,000
19! = 121,645,100,408,832,000
20! = 2,432,902,008,176,640,000
21! = 4,249,290,049,419,214,848
22! = 1,250,660,718,674,968,576
23! = 8,128,291,617,894,825,984
24! = 7,835,185,981,329,244,160
25! = 7,034,535,277,573,963,776

21的结果!是错误的(应该是51,090,942,171,709,440,000),结果22完全变成了麻烦!以上.谁能解释为什么?

The result for 21! is wrong (it should be 51,090,942,171,709,440,000), and the result becomes completely haywire for 22! and above. Can anyone explain why?

推荐答案

您可以长时间代表 -9,223,372,036,854,775,808 +9,223,372,036,854,775,807 (

With long you can represent between -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (source)so as soon the factorial pass that range you start to get errors.

这篇关于阶乘函数对21产生错误的结果!以上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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