Answers:
该BigDecimal
所以你需要做的,这是不变的:
BigDecimal result = test.add(new BigDecimal(30));
System.out.println(result);
从这里的Java文档看来,add返回了一个新的BigDecimal:
BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);
BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);
实际上很简单。只是这样做:
BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);
您也可以这样做:
BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);
印刷品:
A + B + C = 60000000000
只是要添加的另一个示例BigDecimals
。关键是它们是不可变的,只能在构造函数中初始化。这是代码:
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner sc;
boolean first_right_number = false;
BigDecimal initBigDecimal = BigDecimal.ZERO;
BigDecimal add1 = BigDecimal.ZERO;
BigDecimal add2 = BigDecimal.ZERO;
while (!first_right_number)
{
System.out.print("Enter a first single numeric value: ");
sc = new Scanner(System.in);
if (sc.hasNextBigDecimal())
{
first_right_number = true;
add1 = sc.nextBigDecimal();
}
}
boolean second_right_number = false;
while (!second_right_number)
{
System.out.print("Enter a second single numeric value: ");
sc = new Scanner(System.in);
if (sc.hasNextBigDecimal())
{
second_right_number = true;
add2 = sc.nextBigDecimal();
}
}
BigDecimal result = initBigDecimal.add(add1).add(add2);
System.out.println("Sum of the 2 numbers is: " + result.toString());
}
}
add(..)
:“ augend-要添加到此 BigDecimal的值”。此外,说“ ...返回一个新的 BigDecimal ...”而不是“ ...返回一个BigDecimal ...”将是一个不错的感觉。也许我只是在挑剔,但恕我直言,这里还有待改进的地方:-)