本题的关键在于Java中如何保留有效位数
String ans = 6.956231;
BigDecimal b = new BigDecimal(String.valueOf(ans));
BigDecimal divisor = BigDecimal.ONE;
MathContext mc = new MathContext(6); // 保留几位就把2改成几
System.out.println(b.divide(divisor, mc));
下面是代码示例:
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.util.Scanner;
public class P5714肥胖问题 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
double m = sc.nextDouble();
double h = sc.nextDouble();
double ans = m / (h * h);
if (ans < 18.5) {
System.out.println("Underweight");
} else if (ans >= 18.5 && ans < 24) {
System.out.println("Normal");
} else {
BigDecimal b = new BigDecimal(String.valueOf(ans));
BigDecimal divisor = BigDecimal.ONE;
MathContext mc = new MathContext(6); // 保留几位就把2改成几
System.out.println(b.divide(divisor, mc));
System.out.println("Overweight");
}
}
}