[英]Why isn't the divide() function working in Java BigInteger?
I'm attempting to divide the variable 'c' by 2(stored in 'd'). 我正在尝试将变量'c'除以2(存储在'd'中)。 For some reason that doesn't happen.
由于某种原因,这不会发生。 I'm passing 10 and 2 for input right now.
我现在传递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);
}
}
Any help would be appreciated. 任何帮助,将不胜感激。 Thanks in advance!
提前致谢!
You are forgetting that BigInteger
is immutable. 您忘记了
BigInteger
是不可变的。 That means that a.divide(b)
does not change a
it returns the result of the calculation . 这意味着
a.divide(b)
不会改变a
它会返回 计算结果 。
You need a = a.divide(b)
or similar. 您需要
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);
BigInteger
is immutable. BigInteger
是不可变的。 You get the result of c.divide(d);
您得到
c.divide(d);
的结果c.divide(d);
as the return value, which you throw away in your code. 作为返回值,您将其丢弃在代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.