繁体   English   中英

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

[英]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是不可变的。 这意味着a.divide(b) 不会改变a它会返回 计算结果

您需要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是不可变的。 您得到c.divide(d);的结果c.divide(d); 作为返回值,您将其丢弃在代码中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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