计算商数和余数的Java程序

153 阅读1分钟

写一个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);
}

image.png

试试另一个值。

Enter the First Value =  200
Enter the Second Value = 5

Quotient of 200 and 5 = 40
Remainder of 200 and 5 = 0

在这个Java例子中,我们创建了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