用java编写以下内容:编写一个类MyMath,实现四则运算的功能
时间: 2024-05-02 10:20:47 浏览: 13
好的,以下是Java代码实现:
```
public class MyMath {
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) {
return num1 / num2;
}
}
```
这个类实现了四个方法,分别对应加法、减法、乘法和除法,可以传入两个数字作为参数,返回它们的运算结果。
相关问题
java编写一个类方法
以下是一个Java类,其中包含一个静态方法:
```java
public class MyMath {
// 定义一个静态方法,用于计算两个数的和
public static int add(int a, int b) {
return a + b;
}
}
```
使用该类中的add方法,计算两个数的和:
```java
int sum = MyMath.add(2, 3);
System.out.println(sum); // 输出5
```
用python定义一个类MyMath,提供基本的加减乘除功能,并进行测试。
好的,以下是用 Python 定义一个类 MyMath,提供基本的加减乘除功能,并进行测试的代码:
```python
class MyMath:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y == 0:
raise ValueError("Cannot divide by zero!")
return x / y
# 测试
math = MyMath()
print(math.add(2, 3)) # 输出 5
print(math.subtract(5, 2)) # 输出 3
print(math.multiply(4, 6)) # 输出 24
print(math.divide(10, 2)) # 输出 5.0
```
希望这个代码能够满足您的需求。