当结果应为正整数时,方法将产生不变的结果

时间:2019-06-16 02:43:31

标签: java types

情况:

尝试测试以下代码,但是发生了一些奇怪的事情,我不明白为什么:

public static void main(String[] args){
    int x = 30;
    if(product_n(x)>1000000)
        System.out.println("yes " + product_n(x));

    else
        System.out.println("nope "+ product_n(x));
}
// the following method returns the product of the n first integers(excluding 0)
public static int product_n(int n)
{
    int product = 1;
    if (n<=0)
        return 0;
    for(int i = n; i>(n-n);i--)
        product *=i;
    return product;
}

以下数字的结果:

30: 1409286144
31: 738197504
32,33: -2147483648
34: 0

从逻辑上讲,当我增加x时,该方法应返回一个大于前一个整数的整数。我猜想这与变量可以容纳的最大字节数有关。那么什么可以解释31,32,33,34的行为。如果要解决此问题,是否应该将类型从int更改为long?

1 个答案:

答案 0 :(得分:2)

尝试使用double。

int变量占用4个字节,并且可以存储以下范围内的数字:

-2,147,483,648 to 2,147,483,647

这不足以存储30的阶乘

2.652528598E+32

双精度变量占用8个字节,并且可以存储以下范围内的数字:

±1.79769313486231570E+308

代码:

public class MyClass {
    public static void main(String[] args){
    double x = 30;
    if(product_n(x)>1000000)
        System.out.println("yes " + product_n(x));

    else
        System.out.println("nope "+ product_n(x));
}
// the following method returns the product of the n first integers(excluding 0)
public static double product_n(double n)
{
    double product = 1;
    if (n<=0)
        return 0;
    for(double i = n; i>(n-n);i--)
        product *=i;
    return product;
}
}

输出:

yes 2.652528598121911E32

在某些情况下,您将输出视为负数,因为:

  

您需要存储结果的位数少于   可用号码。在这种情况下,会发生溢出。当溢出   碰巧,它只存储了一部分位。假设您需要40位   存储答案,但您只存储了32个。这32位   在某些情况下变成负数。