题解 | #取近似值#
取近似值
https://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);
String resStr = in.next();
int index = resStr.indexOf(".");
int result = 0;
if ((int)(resStr.charAt(index + 1) - '0') >=
5) {//Integer.parseInt是将字符串类型值转化成int类型
result = Integer.parseInt(resStr.substring(0, index)) + 1;
} else {
result = Integer.parseInt(resStr.substring(0, index));
}
System.out.println(result);
}
}
这是牛客上的第一题,主要是先熟悉牛客的提交环境。
输入使用Scanner,输出使用System.out.println()。
Scanner遇到了字符串肯定会使用API中定义好的next()和nextLine()方法。next()是不能读取空格,nextLine()是能读取空格。
一些关于String的API总结:
string.indexOf() :参数为子字符串,获取字符串中某个子字符串的起始下标。
string.charAt() :参数为下标,获取字符串中对应下标的字符对象。
string.contains():参数为子字符串,判断字符串对应中是否含有对应的子字符串对象。
string.substring(1,2): 参数为2个int类型对象,左含右不含,获取对应左右下标范围内的子字符串。
string.substring(1): 参数为1个int类型对象,获取从此下标开始到原字符串末尾(包含末尾字符)的子字符串。