为什么周长会这样输出.多了几个零还有后面的数字public class Circle{ final static double pi=3.14; double r; double c = 1.0; public Circle(double r) { this.r=r; } public double perimeter() { return pi*c*2*c; } public double area()
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/21 02:27:39
为什么周长会这样输出.多了几个零还有后面的数字public class Circle{ final static double pi=3.14; double r; double c = 1.0; public Circle(double r) { this.r=r; } public double perimeter() { return pi*c*2*c; } public double area()
为什么周长会这样输出.多了几个零还有后面的数字
public class Circle
{
final static double pi=3.14;
double r;
double c = 1.0;
public Circle(double r)
{
this.r=r;
}
public double perimeter()
{
return pi*c*2*c;
}
public double area()
{
return pi*this.r*this.r;
}
public static void main(String []args)
{
Circle c1 = new Circle(10.0);
Circle c2 = new Circle(20.0);
System.out.println("半径10周长:"+c1.perimeter());
System.out.println("半径10面积:"+c1.area());
System.out.println("半径20面积:"+c2.area());
System.out.println("半径20周长:"+c2.perimeter());
}
}
我试了很多方法,反正只有两个r相乘才不会有这几个零
为什么周长会这样输出.多了几个零还有后面的数字public class Circle{ final static double pi=3.14; double r; double c = 1.0; public Circle(double r) { this.r=r; } public double perimeter() { return pi*c*2*c; } public double area()
这个可以认为是JAVA的DOUBLE类型的bug.
如果使用java.math.BigDecimal 处理,
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class Circle{
final static double pi=3.14;
double r;
public Circle(double r){
this.r=r;
}
public double perimeter(){
BigDecimal a = new BigDecimal(pi).multiply(new BigDecimal(r)).multiply(new BigDecimal(2D));
return round(a, 2);
}
public double area(){
BigDecimal a = new BigDecimal(pi).multiply(new BigDecimal(r)).multiply(new BigDecimal(r));
return round(a, 2);
}
static double round(BigDecimal a, int scale){
String sNumericalValue = a.toPlainString();
String[] arrayValues = { "", "" };
if (!(sNumericalValue.indexOf(".") < 0)) {
arrayValues = sNumericalValue.split("\\.");
} else {
arrayValues[0] = sNumericalValue;
}
if (arrayValues[0].contains("-")) {
arrayValues[0] = arrayValues[0].replaceAll("-", "");
}
int intLength = arrayValues[0].length();
MathContext context = new MathContext(intLength + scale, RoundingMode.HALF_UP);
return a.round(context).doubleValue();
}
public static void main(String []args){
Circle c1 = new Circle(10.0);
Circle c2 = new Circle(20.0);
System.out.println("半径10周长:"+c1.perimeter());
System.out.println("半径10面积:"+c1.area());
System.out.println("半径20面积:"+c2.area());
System.out.println("半径20周长:"+c2.perimeter());
}
}