Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바(Java)로 몫과 나머지를 계산하는 프로그램 작성하기

이 글에서는 자바(Java)에서 나눗셈의 몫(Quotient)나머지(Remainder)를 계산하는 방법을 알아보겠습니다. 몫과 나머지는 아래와 같은 두 가지 간단한 공식으로 구할 수 있습니다.

  • 몫(Quotient) = 피제수(Dividend) ÷ 제수(Divisor)
  • 나머지(Remainder) = 피제수 % 제수

몫과 나머지의 수학적 원리

정수 a와 0이 아닌 정수 d가 주어졌을 때, a = qd + r이면서 0 ≤ r < |d|를 만족하는 유일한 정수 q와 r이 반드시 존재합니다. 수학적으로 이 조건을 만족하는 q와 r은 하나뿐이며, 여기서 q를 , r을 나머지라고 부릅니다.

아래는 실제 계산 과정에 대한 예시입니다.

자바(Java)로 몫과 나머지를 계산하는 프로그램 작성하기

입력 예시

피제수 값: 50
제수: 3

출력 결과

몫: 16
나머지: 2

알고리즘

프로그램의 전체적인 동작 흐름은 다음과 같습니다.

  1. 시작
  2. 네 개의 정수 변수 my_dividend(피제수), my_divisor(제수), my_quotient(몫), my_remainder(나머지)를 선언합니다.
  3. 사용자에게 두 개의 정수 값을 입력받거나, 코드 내에서 직접 값을 정의합니다.
  4. 값을 읽어 들입니다.
  5. 공식 "몫 = 피제수 / 제수", "나머지 = 피제수 % 제수"를 이용해 몫과 나머지를 계산합니다.
  6. 결과를 화면에 출력합니다.
  7. 종료

예제 1: Scanner로 사용자 입력 받기

이 예제에서는 Scanner 클래스를 사용해 사용자가 직접 값을 입력하면 그에 따른 결과를 출력합니다. 온라인 코딩 도구에서 직접 실행해 볼 수도 있습니다.

import java.util.Scanner;
public class RemainderQuotient {
   public static void main(String[] args) {
      int my_dividend , my_divisor, my_quotient, my_remainder;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A scanner object has been defined ");
      System.out.print("Enter the value of dividend : ");
      my_dividend = my_scanner.nextInt();
      System.out.print("Enter the value of divisor : ");
      my_divisor = my_scanner.nextInt();
      my_quotient = my_dividend / my_divisor;
      my_remainder = my_dividend % my_divisor;
      System.out.println("The quotient is " + my_quotient);
      System.out.println("The remainder is " + my_remainder);
   }
}

실행 결과

Required packages have been imported
A reader object has been defined
Enter the value of dividend : 50
Enter the value of divisor : 3
The quotient is 16
The remainder is 2

예제 2: 값이 미리 정의된 경우

이번에는 사용자 입력 없이, 정수 값이 코드 안에서 미리 정의되어 있고 그 값을 읽어 콘솔에 바로 출력하는 방식입니다.

public class RemainderQuotient {
    public static void main(String[] args) {
       int my_dividend , my_divisor, my_quotient, my_remainder;
       my_dividend = 50;
       my_divisor = 3;
       System.out.println("The divident and the divisor are defined as " +my_dividend +" and " +my_divisor);
       my_quotient = my_dividend / my_divisor;
       my_remainder = my_dividend % my_divisor;
       System.out.println("The quotient is " + my_quotient);
       System.out.println("The remainder is " + my_remainder);
    }
}

실행 결과

The divident and the divisor are defined as 50 and 3
The quotient is 16
The remainder is 2

정리

자바에서 몫은 나누기 연산자(/)로, 나머지는 모듈로 연산자(%)로 손쉽게 구할 수 있습니다. 두 연산자는 정수형(int) 연산에서 특히 유용하며, 짝수·홀수 판별, 순환 로직, 시간 단위 변환 등 다양한 상황에서 활용됩니다. 사용자 입력을 받는 방식과 값을 직접 정의하는 방식 두 가지 모두 상황에 맞게 선택하여 사용하시면 됩니다.