处理浮点数运算不精确的问题
作者:互联网
BigDecimal对象(该类常用来解决浮点数运算不精确的问题)
代码测试:
package cn.tedu.api;
import java.math.BigDecimal;
import java.util.Scanner;
public class TestBigDecimal {
public static void main(String [] args){
f1();//使用普通的四则运算
f2();//使用BigDecimal解决浮点数不精确的问题
}
public static void f1(){
System.out.println("请你输入两个小数:");
double a=new Scanner(System.in).nextDouble();
double b=new Scanner(System.in).nextDouble();
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
}
public static void f2(){
System.out.println("请你输入两个小数:");
double a=new Scanner(System.in).nextDouble();
double b=new Scanner(System.in).nextDouble();
System.out.println(new BigDecimal(a+"").add(new BigDecimal(b+"")));
System.out.println(new BigDecimal(a+"").subtract(new BigDecimal(b+"")));
System.out.println(new BigDecimal(a+"").multiply(new BigDecimal(b+"")));
System.out.println(new BigDecimal(a+"").divide(new BigDecimal(b+""),3,BigDecimal.ROUND_HALF_UP));
}
}
标签:BigDecimal,浮点数,System,Scanner,精确,println,new,out,运算 来源: https://www.cnblogs.com/hanmopx/p/15465212.html