简体   繁体   English

为什么在Java BigInteger中divide()函数不起作用?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM