我有一个作业,我需要从用户那里获得一个输入,以优化对x(用户输入)小数位数的回答。我要改进我的答案,直到x小数位没有任何变化。你能帮忙我怎样才能得到这个答案吗?
答案 0 :(得分:0)
目前还不是很清楚你想要实现的目标,但我认为你想接受一个数字,然后在用户指定时将其四舍五入。
Java的BigDecimal http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html类具有为此目的可能需要的所有功能。请不要使用主要数据类型(float,double),因为它们迟早会导致舍入错误。
答案 1 :(得分:0)
虽然@Thihara的回答是正确的,但也许你需要一些更简单的方法。除非您需要BigDecimal
的精度,否则您可以这样做:
int x = 4;
double value = 3.141593;
long answer = (long) (value * Math.pow(10, x));
要点是:将值乘以10 ^ x,然后转换为long
(或int
)。当然,这仅适用于小x
。
答案 2 :(得分:0)
这里有很多问题,你应该知道。
首先,如果您使用浮点数来表示您的答案,则无法表示每个可能的实数,因此您几乎肯定会得到舍入错误。查看http://floating-point-gui.de/以获取有关此内容的详细信息。
其次,当您打印float
或double
值时,Java会使用它做一些魔术,因此它看起来不错。有关详细信息,请参阅Float.toString(float)
和Double.toString(double)
。
所以实际上,如果你输入
double answer = 3.14159265;
它存储为
3.141592650000000208621031561051495373249053955078125
你可以用看到
System.out.println(new BigDecimal(answer));
因此,假设您的答案为double
(或float
),则应使用BigDecimal
的{{3}}方法。此外,如果您希望将用户可以选择的小数位数限制为以double
作为字符串打印时可见的数字,请将String.valueOf(answer)
传递给BigDecimal
的构造函数。
这是一个演示如何执行此操作的小程序
public static void main(String[] args) {
double answer = 3.14159265;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = null;
do {
System.out.println("Answer: " + answer);
System.out.println("How many decimal places do you want? ");
try {
input = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (input != null) {
try {
int decimalPlaces = Integer.parseInt(input);
if (decimalPlaces < 0) {
System.out.println("Enter a positive value.");
} else {
BigDecimal scaled = new BigDecimal(
String.valueOf(answer));
if (decimalPlaces > scaled.scale()) {
System.out
.println("Answer does not have that many decimal places.");
} else {
scaled = scaled.setScale(decimalPlaces,
RoundingMode.HALF_EVEN);
System.out.println("Rounded answer: " + scaled);
}
}
} catch (Exception e) {
System.out.println("Not a valid number.");
}
}
} while (input != null);
}
大多数代码都是错误/输入检查。真正的工作是由setScale
完成的。请记住,使用浮点数时有很多边界条件,你应该很好!