编写一个 Java 程序,通过示例计算商和余数。在此编程语言中,我们使用 / 和 % 运算符来查找商和余数。此示例允许用户输入两个整数值并计算它们。
package SimpleNumberPrograms;
import java.util.Scanner;
public class QuotientRemainder {
private static Scanner sc;
public static void main(String[] args) {
int num1, num2, quotient, remainder;
sc = new Scanner(System.in);
System.out.print("Enter the First Value = ");
num1 = sc.nextInt();
System.out.print("Enter the Second Value = ");
num2 = sc.nextInt();
quotient = num1 / num2;
remainder = num1 % num2;
System.out.printf("\nQuotient of %d and %d = %d", num1, num2, quotient);
System.out.printf("\nRemainder of %d and %d = %d", num1, num2, remainder);
}
}

让我尝试另一个值。
Enter the First Value = 200
Enter the Second Value = 5
Quotient of 200 and 5 = 40
Remainder of 200 and 5 = 0
使用函数计算商和余数的程序
在此示例中,我们创建了 calcQuo 和 calcRem 函数来计算并返回商和余数。
package SimpleNumberPrograms;
import java.util.Scanner;
public class QuRem2 {
private static Scanner sc;
public static void main(String[] args) {
int num1, num2;
sc = new Scanner(System.in);
System.out.print("Enter the First Value = ");
num1 = sc.nextInt();
System.out.print("Enter the Second Value = ");
num2 = sc.nextInt();
System.out.printf("\nQuotient = %d", calcQuo(num1, num2));
System.out.printf("\nRemainder = %d", calcRem(num1, num2));
}
public static int calcQuo(int num1, int num2) {
return num1 / num2;
}
public static int calcRem(int num1, int num2) {
return num1 % num2;
}
}
Enter the First Value = 125
Enter the Second Value = 7
Quotient = 17
Remainder = 6