gpt4 book ai didi

java - 为什么使用 BigInteger 的程序不显示任何内容?

转载 作者:行者123 更新时间:2023-12-01 09:56:27 26 4
gpt4 key购买 nike

我的程序显示帕斯卡三角形。为了放大可以计算和显示的三角形部分,我使用 BigInteger 而不是基本类型重写了代码。

代码如下:

import java.math.BigInteger;

public class ptrig {
public static void main(String args[]) {
BigInteger no = BigInteger.valueOf(5);

// Creating the array
String doubledim[][] = new String[no.intValue()][];
BigInteger k;
for (k = BigInteger.ZERO; k.compareTo(no) < 0; k.add(BigInteger.ONE)) {
doubledim[k.intValue()] = new String[k.intValue() + BigInteger.ONE.intValue()];
}

// Assigning values
BigInteger i, j, p, n;
BigInteger l = BigInteger.ONE;
for (i = BigInteger.ZERO; i.compareTo(no) < 0; i.add(BigInteger.ONE)) {
for (j = BigInteger.ZERO; j.compareTo(i.add(BigInteger.ONE)) < 0; j.add(BigInteger.ONE)) {
BigInteger m = i.subtract(j);
if (j.compareTo(m) > 0) {
for (p = BigInteger.ZERO; p.compareTo(m) < 0; p = p.add(BigInteger.ONE)) {
n = i.subtract(p);
l = l.multiply(n);
}
doubledim[i.intValue()][j.intValue()] = l.divide(factorial.factmet(m)).toString();
l = BigInteger.ONE;
}
if (m.compareTo(j) > 0) {
for (p = BigInteger.ZERO; p.compareTo(j) < 0; p = p.add(BigInteger.ONE)) {
n = i.add(p.add(BigInteger.ONE)).subtract(j);
l = l.multiply(n);
}
doubledim[i.intValue()][j.intValue()] = l.divide(factorial.factmet(j)).toString();
l = BigInteger.ONE;
}
if (m.compareTo(j) == 0) {
for (p = BigInteger.ZERO; p.compareTo(j) < 0; p = p.add(BigInteger.ONE)) {
n = i.subtract(p);
l = l.multiply(n);
}
doubledim[i.intValue()][j.intValue()] = l.divide(factorial.factmet(j)).toString();
l = BigInteger.ONE;
}
}
}

// Printing
for (i = BigInteger.ZERO; i.compareTo(no) < 0; i.add(BigInteger.ONE)) {
for (j = BigInteger.ZERO; j.compareTo(i.add(BigInteger.ONE)) < 0; j.add(BigInteger.ONE)) {
System.out.print(doubledim[i.intValue()][j.intValue()] + " ");
}
System.out.println();
}
}
}

问题是它什么也没显示。我在 Stack Overflow 上读到,我需要将数组值转换为字符串才能显示,所以我这样做了。我还检查了 System.out.println 语句 - 它们似乎没问题。错误仍然存​​在。

该算法本身在具有原始类型的先前版本上运行良好。

这里有什么错误?我尽力在网上寻找答案,但找不到。谢谢。

最佳答案

您的 for 循环不会增加它们的索引,因此将永远循环。

i.add(BigInteger.ONE) 不会改变 i,它 creates a new BigInteger and returns it 。如果要增加i的值,则需要编写i = i.add(BigInteger.ONE)

<小时/>

这意味着当您尝试初始化数组时,您将进入无限循环,并永远重新初始化 doubledim[0]

例如

for (k = BigInteger.ZERO; k.compareTo(no) < 0; k.add(BigInteger.ONE)) {
doubledim[k.intValue()] = new String[k.intValue() + BigInteger.ONE.intValue()];
}

应该是

for (k = BigInteger.ZERO; k.compareTo(no) < 0; k = k.add(BigInteger.ONE)) {
doubledim[k.intValue()] = new String[k.intValue() + BigInteger.ONE.intValue()];
}

您还需要同样修复控制数组中数据数量的循环,并稍后在程序中打印其数据。

关于java - 为什么使用 BigInteger 的程序不显示任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37171347/

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