我对舍入算法很好奇,因为在 CS 中我们不得不在不使用数学库的情况下模拟 HP35。我们没有在最终版本中包含舍入算法,但我还是想这样做。
public class Round {
public static void main(String[] args) {
/*
* Rounds by using modulus subtraction
*/
double a = 1.123599;
// Should you port this to another method, you can take this as a parameter
int b = 5;
double accuracy = Math.pow(10, -b);
double remainder = a % accuracy;
if (remainder >= 5 * accuracy / 10) // Divide by ten is important because remainder is smaller than accuracy
a += accuracy;
a -= remainder;
/*
* Removes round off error done by modulus
*/
String string = Double.toString(a);
int index = string.indexOf('.') + b;
string = string.substring(0, index);
a = Double.parseDouble(string);
System.out.println(a);
}
}
这是一个好的算法,还是有更好的算法?我不关心 Java API 中定义的那些,我只想知道它是如何完成的。
[编辑] 这是我在查看 EJP 的答案后想出的代码
public class Round {
public static void main(String[] args) {
double a = -1.1234599;
int b = 5;
boolean negative = a < 0;
if (negative) a = -a;
String string = Double.toString(a);
char array[] = string.toCharArray();
int index = string.indexOf('.') + b;
int i = index;
int value;
if (Character.getNumericValue(array[index +1]) >= 5) {
for (; i > 0; i--) {
value = Character.getNumericValue(array[i]);
if (value != -1) {
++value;
String temp = Integer.toString(value)
array[i] = temp.charAt(temp.length()-1);
if (value <= 9) break;
}
}
}
string = "";
for (int j=0; j < index + 1 ; j++) {
string += array[j];
}
a = Double.parseDouble(string);
if (negative) a =-a;
System.out.println(a);
}
}
最佳答案
float 没有小数位。它们有二元的地方,两者不可比。任何将浮点变量修改为具有特定小数位数的尝试都注定要失败。
转换为十进制基数后,您必须四舍五入到指定的小数位数。
关于Java:双舍入算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30114111/