我正在学习java并且有一些我想写的代码应该在24.9999999到25之间。相反,它会转到8。
import java.io.*;
import java.util.*;
public class RadiusOfCircle
{
public static void main(String args[])
{
Scanner kbInput = new Scanner(System.in);
System.out.print("What is the area? _");
double area = kbInput.nextInt();
System.out.println("Radius of your circle is " + Math.sqrt( area / Math.PI));
double radius = Math.sqrt( area / Math.PI);
System.out.println("\nChecking your work now...\n area = pi*(r^2)\n " + area + " = 3.14 * (" + radius + ")^2");
double radiusSqrd = Math.pow(radius, 2);
System.out.println(" " + area + " = 3.14 * " + radiusSqrd);
System.out.println(" " + area + " = " + Math.PI * radiusSqrd);
System.out.println(area + " = " + (Math.round(radiusSqrd)));
System.out.println("Are the two values the same? \nIf yes, your code is correct! \nIf no, try again!");
}
}
另外,当它要求键盘输入该区域时,我输入了25。
这是输出:
What is the area? _25 Radius of your circle is 2.8209479177387813 Checking your work now... area = pi*(r^2) 25.0 = 3.14 * (2.8209479177387813)^2 25.0 = 3.14 * 7.957747154594766 25.0 = 24.999999999999996 25.0 = 8 Are the two values the same? If yes, your code is correct! If no, try again!
答案 0 :(得分:11)
您只是四舍五入radiusSquared
,而不是Math.PI * radiusSquared
。修复应该得到你期望的结果。
答案 1 :(得分:4)
System.out.println(" " + area + " = " + Math.PI * radiusSqrd);
System.out.println(area + " = " + (Math.round(radiusSqrd)));
不应该是:
double value = Math.PI * radiusSqrd;
System.out.println(" " + area + " = " +value );
System.out.println(area + " = " + (Math.round(value )));
答案 2 :(得分:2)
您省略乘以PI
:
System.out.println(area + " = " + Math.round(Math.PI * radiusSqrd));
执行此操作会得到预期的结果。
答案 3 :(得分:1)
float
和double
是针对工程问题而设计的,它具有10的大正功率......它们不能准确地表达10的负幂。在这种情况下,请使用BigDecimal
。
从Joshua Bloch的书“Effective Java”中运行这个简单的代码,以了解在处理负面权力时使用double
存储它们时的不准确性的延伸。答案应该是zero
,但结果却完全是另一回事!
double funds = 1.00;
int itemsBought = 0;
for (double price = .10; funds >= price; price += .10) {
funds -= price;
itemsBought++;
}
System.out.println(itemsBought + ” items bought.”);
System.out.println(“Change: $” + funds);
}
答案 4 :(得分:0)
如果要在Java中使用“准确”数学,则应使用BigDecimal类,而不是内置浮点基元类型。由于浮点运算的本质,double和float 总是会出现这样的问题。
请注意,BigDecimal的推荐构造函数使用String,而不是任何数字类型。由于您从控制台获得输入,因此应该易于实现。
答案 5 :(得分:0)
您可以使用以下内容:
double d = 10.938;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(0,BigDecimal.ROUND_HALF_UP);
System.out.println(bd);
bd = new BigDecimal(d);
bd = bd.setScale(1,BigDecimal.ROUND_HALF_UP);
System.out.println(bd);
bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
System.out.println(bd);
或者像这样:
double d = 10.938;
DecimalFormat decimalFormat = new DecimalFormat("#");
System.out.println(decimalFormat.format(d));
decimalFormat = new DecimalFormat("#.#");
System.out.println(decimalFormat.format(d));
decimalFormat = new DecimalFormat("#.##");
System.out.println(decimalFormat.format(d));