用Java编写.求两个数据之和(整数和小数) 2.判断两个数据是否相等(整数和小数) 3.获取两个数中较大的值(整数和小数) 4.获取两个数中较小的值(整数和小数) 5.否能用一个方法实现3和4的两个功能
时间: 2024-02-11 17:05:30 浏览: 88
1. 计算两个数据之和:
```java
public class Main {
public static void main(String[] args) {
int a = 3;
int b = 5;
double c = 2.5;
double d = 6.7;
int sum1 = add(a, b);
double sum2 = add(c, d);
System.out.println("sum1 = " + sum1);
System.out.println("sum2 = " + sum2);
}
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
}
```
2. 判断两个数据是否相等:
```java
public class Main {
public static void main(String[] args) {
int a = 3;
int b = 5;
double c = 2.5;
double d = 6.7;
boolean equal1 = isEqual(a, b);
boolean equal2 = isEqual(c, d);
System.out.println("equal1 = " + equal1);
System.out.println("equal2 = " + equal2);
}
public static boolean isEqual(int a, int b) {
return a == b;
}
public static boolean isEqual(double a, double b) {
return a == b;
}
}
```
3. 获取两个数中较大的值:
```java
public class Main {
public static void main(String[] args) {
int a = 3;
int b = 5;
double c = 2.5;
double d = 6.7;
int max1 = getMax(a, b);
double max2 = getMax(c, d);
System.out.println("max1 = " + max1);
System.out.println("max2 = " + max2);
}
public static int getMax(int a, int b) {
return Math.max(a, b);
}
public static double getMax(double a, double b) {
return Math.max(a, b);
}
}
```
4. 获取两个数中较小的值:
```java
public class Main {
public static void main(String[] args) {
int a = 3;
int b = 5;
double c = 2.5;
double d = 6.7;
int min1 = getMin(a, b);
double min2 = getMin(c, d);
System.out.println("min1 = " + min1);
System.out.println("min2 = " + min2);
}
public static int getMin(int a, int b) {
return Math.min(a, b);
}
public static double getMin(double a, double b) {
return Math.min(a, b);
}
}
```
5. 可以用一个方法实现3和4的两个功能,如下所示:
```java
public class Main {
public static void main(String[] args) {
int a = 3;
int b = 5;
double c = 2.5;
double d = 6.7;
int max1 = getExtremeValue(a, b, true);
double max2 = getExtremeValue(c, d, true);
int min1 = getExtremeValue(a, b, false);
double min2 = getExtremeValue(c, d, false);
System.out.println("max1 = " + max1);
System.out.println("max2 = " + max2);
System.out.println("min1 = " + min1);
System.out.println("min2 = " + min2);
}
public static <T extends Number> T getExtremeValue(T a, T b, boolean isMax) {
if (isMax) {
return a.doubleValue() > b.doubleValue() ? a : b;
} else {
return a.doubleValue() < b.doubleValue() ? a : b;
}
}
}
```
其中,`getExtremeValue` 方法使用了泛型,可以接受任何 Number 类型的参数,并根据第三个参数 `isMax` 来决定返回两个数中较大还是较小的值。
阅读全文