数组重载加减

题目:

数组重载加减

Time/Memory Limit:1000 MS/32768 K
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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值