How to determine negative number and positive number in Java?
2011-12-11 22:22
357 查看
This is Java code:
The output is:
package com.test.day13.num; /** * @author BigBird * @date 2011-12-11 下午10:12:33 * @action 测试判断一个数是正数还是负数 */ public class NumTest { public static boolean positive(double f) { final boolean pos0[] = {true}; final boolean posn[] = {false, true}; if (f == 0.0) return true; while (true) { // If f is in ]-1.0; 1.0[, multiply it by 2 and restart. try { if (pos0[(int) f]) { f *= 2.0; continue; } } catch (Exception e) { } // If f is in ]-2.0; -1.0] U [1.0; 2.0[, return the proper answer. try { return posn[(int) ((f+1.5)/2)]; } catch (Exception e) { } // f is outside ]-2.0; 2.0[, divide by 2 and restart. f /= 2.0; } } static void check(double f) { System.out.println(f + " -> " + positive(f)); } public static void main(String args[]) { for (double i = -10.0; i <= 10.0; i++) check(i); check(-1e24); check(-1e-24); check(1e-24); check(1e24); } }
The output is:
-10.0 -> false -9.0 -> false -8.0 -> false -7.0 -> false -6.0 -> false -5.0 -> false -4.0 -> false -3.0 -> false -2.0 -> false -1.0 -> false 0.0 -> true 1.0 -> true 2.0 -> true 3.0 -> true 4.0 -> true 5.0 -> true 6.0 -> true 7.0 -> true 8.0 -> true 9.0 -> true 10.0 -> true -1.0E24 -> false -1.0E-24 -> false 1.0E-24 -> true 1.0E24 -> true
相关文章推荐
- How to convert negative number to positive in Java?
- How to check if a Number is Positive or Negative in Java - Interview Question
- Java: How to compile and run Java application in command line(在命令行中编译运行java程序)
- How to use ConcurrentHashMap in Java - Example Tutorial and Working
- how to save a c++ object in java object and use it
- How to run Java main class and pass application arguments in Maven?
- Units Problem: How to read text size as custom attr from xml and set it to TextView in java code
- Units Problem: How to read text size as custom attr from xml and set it to TextView in java code
- How to read and parse CSV file in Java
- How to create Immutable Class and Object in Java - Tutorial Example
- How to Determine if a file is a .Net assembly (in Delphi and C#)
- How to implement equals() and hashCode() methods in Java[reproduced]
- How to compile and run a simple java file in jenkins on Windows
- How to run java and junit in command line
- How to check for and disable Java in OS X
- How to determine if a driver should have been registered in kernel and lspci vs pci_device_id
- How to use equals( ) and equalsIgnoreCase( ) in Java
- How to read and write JSON files in Java(Gson)
- How to Create and Evaluate XPath Expression in Java - Tutorial and Example
- How-To : Using EJB 3.0 and Java Persistence API with Spring in OC4J