AcWing-739. 陣列選擇
阿新 • • 發佈:2022-01-15
AcWing-739-陣列選擇
這裡主要是為了記錄如何格式化輸出以及比較浮點數的大小。因為在計算機中不是所有浮點數都可以精確的表示,所以在比較浮點數時,通常會讓兩個浮點數之差小於一個很小的數,達到比較的效果。
而格式化輸入也只需要指定格式和要輸出的物件即可。
import java.io.*; import java.util.*; public class Main { public static final double zero = (1e-6); public static void main(String[] args) { Reader r = new Reader(); Writer w = new Writer(); double[] arr = new double[100]; for(int i = 0; i < 100; i++) { arr[i] = r.nextDouble(); } for(int i = 0; i < 100; i++) { if((arr[i] - 10) < zero) { w.printf("A[%d] = %.1f\n",i, arr[i]); } } w.flush(); r.close(); w.close(); } public static class Reader { public BufferedReader in; public StringTokenizer tokenizer; public Reader() { in = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException ex) { throw new RuntimeException(ex); } } return tokenizer.nextToken(); } public String nextLine() { String str = null; try { str = in.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } return str; } public boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String str = nextLine(); if (str == null) { return false; } tokenizer = new StringTokenizer(str); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public void close() { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } public static class Writer { public PrintWriter out; public Writer() { this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } public void flush() { out.flush(); } public void print(char obj) { out.write(obj); } public void print(String obj) { out.write(obj); } public void println(String str) { out.write(str + "\n"); } public void println(Object obj) { out.write(obj + "\n"); } public void printf(String format, Object... objs) { out.printf(format, objs); } public void close() { out.close(); } } }