How to determine negative number and positive number in Java?

來源:互聯網
上載者:User

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 -> false0.0 -> true1.0 -> true2.0 -> true3.0 -> true4.0 -> true5.0 -> true6.0 -> true7.0 -> true8.0 -> true9.0 -> true10.0 -> true-1.0E24 -> false-1.0E-24 -> false1.0E-24 -> true1.0E24 -> true

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.