輸入十進位整數,選擇轉換的進制(二進位、八進位、十六進位)
import java.util.Scanner;
public class test
{
public static void main
(String args
[])
{
int num = 0 , n = 0 ;
String ans
= "" , hex
[] = {"A",
"B",
"C",
"D",
"E",
"F"};
System.
out.
print("請輸入一個10進位的正整數=>") ;
Scanner temp
= new Scanner
(System.
in) ;
num = temp.nextInt() ;
do
{
System.
out.
print("要轉成多少進位數? (1)2進位 (2)8進位 (3)16進位=>") ;
temp
= new Scanner
(System.
in) ;
n = (int)temp.nextInt() ;
}while( n < 1 && n > 3 );
switch( n )
{
case 1:
n = 2 ;
break ;
case 2:
n = 8 ;
break ;
case 3:
n = 16 ;
break ;
}
while( num != 0 )
{
if( num % n >= 10 )
{
ans = hex[ (num % n -10) ] + ans ;
}
else
{
ans = num % n + ans ;
}
num = num / n;
}
}
}
沒有留言:
張貼留言