题解 | #取近似值# 学习牛客大佬们的代码

取近似值

https://www.nowcoder.com/practice/3ab09737afb645cc82c35d56a5ce802a

import java.io.InputStream;

public class Main {
    public static void main(String[] args) throws Exception {
        // 获取标准输入流
        InputStream in = System.in;

        // 从输入流中读取一个字节的数据
        int c = (int) in.read();

        // 初始化结果变量和临时变量
        int ans = 0;
        int temp = 0;

        // 循环读取输入流中的数据,直到遇到换行符
        while (c != '\n') {
            // 判断当前字符是否为小数点
            if (temp == 1) {
                // 如果当前字符为小数点且后续字符的 ASCII 值大于 52(代表大于 '4')
                if ((int) c > 52) {
                    ans += 1;
                }
                // 输出结果并跳出循环
                System.out.println(ans);
                break;
            } else if (temp == 0) {
                // 如果临时变量为 0,表示当前处理整数部分
                if (c == '.') {
                    // 如果遇到小数点,将临时变量设为 1,表示开始处理小数部分
                    temp = 1;
                } else {
                    // 如果当前字符为数字字符,则将其转换为数字并添加到结果中
                    ans = ans * 10 + (int) (c - 48);
                }
            }

            // 继续读取下一个字符
            c = (char) in.read();
        }

        // 如果循环结束时临时变量仍为 0,表示没有小数部分,输出结果
        if (temp == 0) {
            System.out.println(ans);
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务