为什么 divide() 函数在 Java BigInteger 中不起作用?
Why isn't the divide() function working in Java BigInteger?
我正在尝试将变量 'c' 除以 2(存储在 'd' 中)。由于某种原因,这不会发生。我现在正在传递 10 和 2 进行输入。
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
BigInteger a = new BigInteger(sc.next());
BigInteger b = sc.nextBigInteger();
BigInteger d = new BigInteger("2");
System.out.println(d);
BigInteger c = a.subtract(b);
c.divide(d);
System.out.println(c);
a.subtract(c);
System.out.println(a);
System.out.println(c);
}
}
如有任何帮助,我们将不胜感激。提前致谢!
BigInteger
是不可变的。您将 c.divide(d);
的结果作为 return 值,您将其丢弃在代码中。
您忘记了 BigInteger
是不可变的。这意味着 a.divide(b)
不会改变 a
它 returns 的 结果计算.
您需要 a = a.divide(b)
或类似的。
BigInteger a = new BigInteger(sc.next());
BigInteger b = sc.nextBigInteger();
BigInteger d = new BigInteger("2");
System.out.println(d);
BigInteger c = a.subtract(b);
// HERE!
c = c.divide(d);
System.out.println(c);
// HERE!
a = a.subtract(c);
System.out.println(a);
System.out.println(c);
我正在尝试将变量 'c' 除以 2(存储在 'd' 中)。由于某种原因,这不会发生。我现在正在传递 10 和 2 进行输入。
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
BigInteger a = new BigInteger(sc.next());
BigInteger b = sc.nextBigInteger();
BigInteger d = new BigInteger("2");
System.out.println(d);
BigInteger c = a.subtract(b);
c.divide(d);
System.out.println(c);
a.subtract(c);
System.out.println(a);
System.out.println(c);
}
}
如有任何帮助,我们将不胜感激。提前致谢!
BigInteger
是不可变的。您将 c.divide(d);
的结果作为 return 值,您将其丢弃在代码中。
您忘记了 BigInteger
是不可变的。这意味着 a.divide(b)
不会改变 a
它 returns 的 结果计算.
您需要 a = a.divide(b)
或类似的。
BigInteger a = new BigInteger(sc.next());
BigInteger b = sc.nextBigInteger();
BigInteger d = new BigInteger("2");
System.out.println(d);
BigInteger c = a.subtract(b);
// HERE!
c = c.divide(d);
System.out.println(c);
// HERE!
a = a.subtract(c);
System.out.println(a);
System.out.println(c);