本文主要是介绍数组重载加减,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
数组重载加减
Time/Memory Limit:1000 MS/32768 K
Submitted: 38 Accepted: 22
Submitted: 38 Accepted: 22
Problem Description
定义一个shuzu类,编写一个程序,含有默认构造函数(将数组每个元素初始为0),构造函数,用成员函数运算符重载“+”和“-”,实现将两个一维数组相加和相减。
Input
第一行输入一个数t,代表t组测试数据,每组数据先输入一个整数N(0<N<=100)代表两个数组的长度,接着依次输入两个数组。
Output
每组输出占两行,分别为两个数组加减后的结果。(减法默认第一个数组的每个元素为被减数)每个数后面带一个空格。
Sample Input
2
2
5 6
3 2
3
1 2 3
3 2 1
Sample Output
8 8
2 4
4 4 4
-2 0 2
参考代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
class Matrix
{
private:
int num, array[200];
public:
Matrix();
Matrix(int n, int a[200]);
Matrix(Matrix&);
Matrix operator+(const Matrix&);
Matrix operator-(const Matrix&);
void show();
};
Matrix::Matrix()
{
num = 0;
for (int i = 0; i < num; i++)
array[i] = 0;
}
Matrix::Matrix(int n, int* a)
{
num = n;
for (int i = 0; i < num; i++)
array[i] = a[i];
}
Matrix::Matrix(Matrix& c)
{
num = c.num;
for (int i = 0; i < c.num; i++)
array[i] = c.array[i];
}
Matrix Matrix::operator+(const Matrix& c)
{
Matrix x;
x.num = c.num;
for (int i = 0; i < num; i++)
x.array[i] = array[i] + c.array[i];
return x;
}
Matrix Matrix::operator-(const Matrix& c)
{
Matrix x;
x.num = c.num;
for (int i = 0; i < num; i++)
x.array[i] = array[i] - c.array[i];
return x;
}
void Matrix::show()
{
int i, k = 0;
for (i = 0; i < num; i++) {
cout << array[k++]<<" ";
}
cout << endl;
}
int main()
{
//freopen("1.txt", "r", stdin);
int t, i, j, n, a[200], b[200];
while (cin >> t) {
while (cin >> n) {
for (i = 0; i < n; i++)
cin >> a[i];
for (j = 0; j < n; j++)
cin >> b[j];
Matrix x(n, a), y(n, b), z, w;
z = x + y;
z.show();
w = x - y;
w.show();
}
}
return 0;
}
这篇关于数组重载加减的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!