java 分解整數 【個 十 百】(數組案例),java數組

來源:互聯網
上載者:User

java 分解整數 【個 十 百】(數組案例),java數組

求一個數兩位元的個位元,十位元及百位元:

   int num = 53;

     int g =  num % 10;              //個位
         int s =  (num / 10) % 10;    //十位
         int b = (num / 100);            //百位

 

下面是用java寫的一個一般般的 拆分整數的案例 值得大夥研究研究,趣味無窮哦

 1 import java.util.Scanner; //匯入輸入庫 2 class numbers 3 { 4     public static void main(String[] args)  5     { 6         //最多輸入十億位 7         //建立一個數組,遍曆輸出相應的位元 8         String[] str = new String[]{"十位","百位","千位","萬位","十萬位","百萬位","千萬位","億位","十億位","百億位","千億位"}; 9 10         System.out.println("請輸入一個數字:");11         Scanner sca = new Scanner(System.in);12 13         //接受使用者輸入的數14         long sum = sca.nextInt(); //聲明一個長整型變數15         long sum2 = sum; //分開判斷正 負數16         int a = 0; 17 18         for (int i = 0 ; i<32 ;i++ )19         {20             //判斷使用者輸入的數是幾位元21             if(sum/10 > 0){ //個位元大於0,為正數22                 sum = sum/10;23                 a++;24             }else{25                 break;26             }27         }28 29         if (sum2 < 10) //如果是負數30         {31             long k = sum;32             System.out.println("這個數只有個位是"+k);//33 34         }else{35             //把使用者輸入的數是分解出來36             for (int i = 0 ;i <= a ;i++ )37             {38                 if (i==0)39                 {40                      long c = sum2 % 10; //個位元41                      System.out.println("這個數的個位是:"+c);42 43                 }else if(i < a){44                    //這裡要強轉一下 這個函數出來的double;45                     long new1 = (long)Math.pow(10,i); 46                          47                     //參數說明:m為要求方的數,n為次方數48                     long b = sum2 / new1 % 10;49                     System.out.println("這個數的"+str[i-1]+"是:"+b);50 51                  }else{                52                     long new2= (long)Math.pow(10,i);53                     long h = sum2 / new2 % 10;54                     System.out.println("這個數的"+str[i-1]+"是:"+h);55                  }56             }57         58         }59 60     }61 }

陌陌說:程式設計語言之間多少都是有相通的,萬變不離其宗,java本是繼承於c,c++,oc等語言,所以根本原理是不變的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.