题解 | #取近似值#
取近似值
http://www.nowcoder.com/practice/3ab09737afb645cc82c35d56a5ce802a
我自己的解法是
用字符串判断
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
if(in.hasNextLine()){
String str = in.nextLine();
String[] spl = str.split("\\.");
if (spl.length == 2){
String r = spl[1];
if (r.startsWith("5") || r.startsWith("6") ||
r.startsWith("7") || r.startsWith("8") ||
r.startsWith("9"))
{
int value = Integer.parseInt(spl[0]);
System.out.println(value + 1);
}
else
{
System.out.println(spl[0]);
}
}
}
}
}这里有另外两种解决方案:
通过double的方式,用Math.round
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
double d = in.nextDouble();
System.out.println(Math.round(d));
}
}
}通过int强转,真是简单粗暴啊
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
if (in.hasNextFloat()){
float f = in.nextFloat();
System.out.println((int)(f+ 0.5));
}
}
}