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