gpt4 book ai didi

java - 当结果应该是正整数时,方法产生不变的结果

转载 作者:行者123 更新时间:2023-12-02 01:27:46 32 4
gpt4 key购买 nike

情况:

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

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 吗?

最佳答案

尝试使用 double 。

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

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

这不足以存储 30 的阶乘,即

2.652528598E+32

double变量占用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

在某些情况下,您会看到输出为负数,因为:

The number of bits you need to store the results is less than the number available. In such a case, overflow happens. When an overflow happens, it just stores a part of the bits. Let's say you need 40 bits to store the answer but you're only storing 32 of them. These 32 bits were turning out to be negative numbers in some cases.

关于java - 当结果应该是正整数时,方法产生不变的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615682/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com