計算商和餘數的Java程式


給定一個整數a和一個非零整數d,我們的任務是編寫一個Java程式來計算商和餘數。商可以使用公式“商 = 被除數 / 除數”計算,而餘數則使用“餘數 = 被除數 % 除數”計算。

當一個數(即被除數)被另一個數(即除數)除時,商是除法的結果,而餘數是如果被除數不能被除數完全整除時剩下的部分。

示例場景

假設我們的輸入是:

Input1: Dividend = 50
Input2: Divisor = 3
Output: Quotient = 16 and Remainder = 2

這裡,我們提供了一個計算商和餘數的工具

商和餘數計算器 - 技術教學

商和餘數計算器


計算商和餘數的程式

下面給出一個Java程式,演示如何計算商和餘數。

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 dividend 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 dividend and the divisor are defined as 50 and 3
The quotient is 16
The remainder is 2

使用者自定義函式

在這裡,我們使用Java中的使用者自定義方法來計算商和餘數:

public class RemainderQuotient {
   public static void main(String[] args) {
      int my_dividend = 47;
      int my_divisor = 3;
      System.out.println("The dividend and the divisor are defined as " + my_dividend + " and " + my_divisor);
      
      int[] result = calc(my_dividend, my_divisor);
      
      System.out.println("The quotient is " + result[0]);
      System.out.println("The remainder is " + result[1]);
   }

   public static int[] calc(int dividend, int divisor) {
      int my_quotient = dividend / divisor;
      int my_remainder = dividend % divisor;
      return new int[]{my_quotient, my_remainder};
   }
}

輸出

The dividend and the divisor are defined as 47 and 3
The quotient is 15
The remainder is 2

更新於:2024年9月13日

988 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告