C++面向对象程序设计习题2:派生数组

C++面向对象程序设计习题2:派生数组

原题链接在此:习题2派生数组

关于动态数组可以参考此博客:细说C++中的数组之动态数组

代码比较简单,直接粘贴在此,文件名为myArray.hpp,最后附有相应的测试代码

//
// Created by believer on 2022/7/4.
//

/*
 * 第二题:派生数组
 * 规则:新数组b的每一个元素等于初始数组a的对应元素及其相邻两元素的平均值
 */

#ifndef OOP_LEARN_MYARRAY_HPP
#define OOP_LEARN_MYARRAY_HPP

#include <iostream>

class myArray{
private:
    float* a;
    float* b;
    int size;
public:
    myArray(int sz = 10);
    ~myArray();
    void process();
    void print() const;
};

myArray::myArray(int sz) : size(sz) {
    // 动态数组创建
    a = new float[size]();
    b = new float[size]();
    std::cout << "输入初始数组的各个值" << std::endl;
    float temp;
    for (int i = 0; i < size; ++i) {
        std::cout << i << ": ";
        std::cin >> temp;
        a[i] = temp;
        std::cout << std::endl;
    }
}

// 动态数组必须手动释放空间
myArray::~myArray() {
    delete []a;
    delete []b;
}

// 平均数规则
void myArray::process() {
    // 第一个数以及最后一个数单独处理
    b[0] = (a[size-1] + a[0] + a[1]) / 3;
    for (int i = 1; i < size - 1; ++i) {
        b[i] = (a[i - 1] + a[i] + a[i + 1]) / 3;
    }
    b[size - 1] = (a[size-2] + a[size-1] + a[0]) / 3;
}

// 将两个数组输出
void myArray::print() const {
    for (int i = 0; i < size; ++i) {
        std::cout << a[i] << ' ';
    }
    std::cout << std::endl;
    for (int i = 0; i < size; ++i) {
        std::cout << b[i] << ' ';
    }
}

#endif //OOP_LEARN_MYARRAY_HPP

/*
 * 测试代码:同级目录创建
#include "myArray.hpp"
#include <iostream>

int main()
{
    myArray newAaary(5);
    newAaary.process();
    newAaary.print();
    return 0;
}
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力攀爬的小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值