用函数重载,实现两个不同类型数据的相加,包括int型,float型,double型,一维和二维数组;编写主函数对重载函数进行测试,要求不使用 vector 函数
时间: 2024-06-13 08:08:30 浏览: 97
两个二维数组相加,用成员函数重载运算符“+”和“-”
5星 · 资源好评率100%
以下是使用函数重载实现两个不同类型数据的相加的示例代码,包括int型,float型,double型,一维和二维数组:
```java
public class Adder {
public int add(int a, int b) {
return a + b;
}
public float add(float a, float b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int[] add(int[] a, int[] b) {
if (a.length != b.length) {
return null;
}
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = a[i] + b[i];
}
return result;
}
public int[][] add(int[][] a, int[][] b) {
if (a.length != b.length || a[0].length != b[0].length) {
return null;
}
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
}
public class Main {
public static void main(String[] args) {
Adder adder = new Adder();
int a = 1, b = 2;
float c = 1.5f, d = 2.5f;
double e = 1.5, f = 2.5;
int[] g = {1, 2, 3}, h = {4, 5, 6};
int[][] i = {{1, 2}, {3, 4}}, j = {{5, 6}, {7, 8}};
System.out.println(adder.add(a, b)); // 输出:3
System.out.println(adder.add(c, d)); // 输出:4.0
System.out.println(adder.add(e, f)); // 输出:4.0
System.out.println(Arrays.toString(adder.add(g, h))); // 输出:[5, 7, 9]
System.out.println(Arrays.deepToString(adder.add(i, j))); // 输出:[[6, 8], [10, 12]]
}
}
```
阅读全文