定义一个类,属性数据包含两个整数,4个函数包含:构造函数,求最大公约数函数,求最小公倍数函数,以及交换两个数值的函数. 主函数生成类的对象,分别求两个数的最大公约数,最小公倍数,以及两个整数的互换
时间: 2024-03-17 16:42:39 浏览: 19
可以参考下面的Java代码实现:
```
public class TwoIntegers {
private int num1;
private int num2;
// 构造函数
public TwoIntegers(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
// 求最大公约数
public int getGreatestCommonDivisor() {
int a = num1;
int b = num2;
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
// 求最小公倍数
public int getLeastCommonMultiple() {
int gcd = getGreatestCommonDivisor();
return num1 * num2 / gcd;
}
// 交换两个数值的函数
public void swap() {
int temp = num1;
num1 = num2;
num2 = temp;
}
public static void main(String[] args) {
TwoIntegers integers = new TwoIntegers(12, 18);
int gcd = integers.getGreatestCommonDivisor();
int lcm = integers.getLeastCommonMultiple();
System.out.println("最大公约数:" + gcd);
System.out.println("最小公倍数:" + lcm);
integers.swap();
System.out.println("交换后的数值:" + integers.num1 + ", " + integers.num2);
}
}
```
在主函数中,我们首先创建一个TwoIntegers的对象,然后调用该类的getGreatestCommonDivisor和getLeastCommonMultiple函数分别求出最大公约数和最小公倍数,并打印输出。接着调用swap函数交换两个整数的数值,并打印输出交换后的数值。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)