输入两个整数num1和num2,请你设计一个程序,计算并输出它们的和、差、积、整数商及余数。java
时间: 2024-09-22 18:04:41 浏览: 59
计算两个整数的和差积商
在Java中,你可以创建一个名为`Calculator`的简单类,包含静态方法来分别计算两个整数的和、差、积、商和余数。下面是一个简单的示例:
```java
public class Calculator {
// 计算两数之和
public static int add(int num1, int num2) {
return num1 + num2;
}
// 计算两数之差
public static int subtract(int num1, int num2) {
return num1 - num2;
}
// 计算两数之积
public static int multiply(int num1, int num2) {
return num1 * num2;
}
// 计算两数除法,整数商
public static int divide(int num1, int num2) {
if (num2 != 0) {
return num1 / num2;
} else {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
}
// 计算两数除法,余数
public static int remainder(int num1, int num2) {
if (num2 != 0) {
return num1 % num2;
} else {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
}
}
```
然后你可以这样使用这个类:
```java
public class Main {
public static void main(String[] args) {
int num1 = 10, num2 = 5;
System.out.println("Sum: " + Calculator.add(num1, num2));
System.out.println("Difference: " + Calculator.subtract(num1, num2));
System.out.println("Product: " + Calculator.multiply(num1, num2));
System.out.println("Quotient: " + Calculator.divide(num1, num2));
System.out.println("Remainder: " + Calculator.remainder(num1, num2));
}
}
```
阅读全文