2014年12月24日 星期三

java程式設計題目---數字處理【十進位轉二進位】

設計一程式,提示使用者輸入正整數n,將該數值轉換成二進位數制,並以16-bit方式於螢幕輸出結果。
例如:輸入18,輸出 0000 0000 0001 0010。


import java.util.Scanner;

public class C1 
{ 
 public static void main(String[] args) 
 {
  Scanner input = new Scanner(System.in);
  
  //提示使用者輸入
  System.out.println("請輸入數字:");
  int number = input.nextInt();
  int quotient = 0;//商數
  String output = " "; 
  
  //計算結果
  for(int n = 1; n <= 4; n++ )//計算每四個字元要空白
  {
   for(int i = 1; i <= 4 ; i ++)
   {
     int remainder = number % 2;//餘數
     quotient = number / 2 ;
     number = quotient;
     output = remainder + output;  
   }  
  
  output = " " + output;//印出空白
   
  }
   
     //印出結果
  System.out.println(output);
 }

}

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

下載MSYS2:  https://www.msys2.org/ 安裝 程式開始執行後輸入: pacman -Syu y y 在安裝目錄底下找到msys2.exe,雙擊執行 輸入指令: pacman -Su pacman -S --needed base-devel mingw-...