How to determine negative number and positive number in Java?

This is Java code:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值