English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 프로그램에서는 Java에서 함수를 사용하여 이진수와 십진수를相互 변환하는 방법을 배울 수 있습니다.
public class BinaryDecimal { public static void main(String[] args) { long num = 110110111; int decimal = convertBinaryToDecimal(num); System.out.printf("%d 이진수 = %d 십진수", num, decimal); } public static int convertBinaryToDecimal(long num) { int decimalNumber = 0, i = 0; long remainder; while (num != 0) { remainder = num % 10; num /= 10; decimalNumber += remainder * Math.pow(2, i); ++i; } return decimalNumber; } }
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
110110111 이진수 = 439 십진수
public class DecimalBinary { public static void main(String[] args) { int num = 19; long binary = convertDecimalToBinary(num); System.out.printf("%d 십진 = %d 이진", num, binary)} } public static long convertDecimalToBinary(int n) { long binaryNumber = 0; int remainder, i = 1, step = 1; while (n!=0) { remainder = n % 2; System.out.printf("단계 %d: %d/2, remainder = %d, quotient = %d\n", step++, n, remainder, n/2); n /= 2; binaryNumber += remainder * i; i *= 10; } return binaryNumber; } }
이 프로그램을 실행할 때, 출력은 다음과 같습니다:
단계 1: 19/2, remainder = 1, quotient = 9 단계 2: 9/2, remainder = 1, quotient = 4 단계 3: 4/2, remainder = 0, quotient = 2 단계 4: 2/2, remainder = 0, quotient = 1 단계 5: 1/2, remainder = 1, quotient = 0 19 십진 = = 10011 이진