初始代码
import java.util.Scanner;
/**
* 9:56
* 近似值,输入数值取整输出,四舍五入
*/
public class Approximate_value_1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextDouble()) {
double d = sc.nextDouble();
System.out.println(Math.round(d));
}
System.out.println("a");
}
}
math.round底层
返回与参数最接近的int ,并把四舍五入到正无穷大。
特别案例:
如果参数为NaN,则结果为0。
如果参数为负无穷大或任何小于或等于Integer.MIN_VALUE的值,则结果等于Integer.MIN_VALUE的值。
如果参数为正无穷大或任何大于或等于Integer.MAX_VALUE的值,则结果等于Integer.MAX_VALUE的值。
参数:
a –要四舍五入为整数的浮点值。
返回值:
参数的值四舍五入到最接近的int值。
public static int round(float a) {
//传入一个float型数a
int intBits = Float.floatToRawIntBits(a);
//传入数值取整
int biasedExp = (intBits & FloatConsts.EXP_BIT_MASK)
>> (FloatConsts.SIGNIFICAND_WIDTH - 1);
int shift = (FloatConsts.SIGNIFICAND_WIDTH - 2
+ FloatConsts.EXP_BIAS) - biasedExp;
if ((shift & -32) == 0) { // shift >= 0 && shift < 32
// a is a finite number such that pow(2,-32) <= ulp(a) < 1
int r = ((intBits & FloatConsts.SIGNIF_BIT_MASK)
| (FloatConsts.SIGNIF_BIT_MASK + 1));
if (intBits < 0) {
r = -r;
}
// In the comments below each Java expression evaluates to the value
// the corresponding mathematical expression:
// (r) evaluates to a / ulp(a)
// (r >> shift) evaluates to floor(a * 2)
// ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2)
// (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2)
return ((r >> shift) + 1) >> 1;
} else {
// a is either
// - a finite number with abs(a) < exp(2,FloatConsts.SIGNIFICAND_WIDTH-32) < 1/2
// - a finite number with ulp(a) >= 1 and hence a is a mathematical integer
// - an infinity or NaN
return (int) a;
}
}
524



被折叠的 条评论
为什么被折叠?



