C++求和操作

【问题描述】

理解主函数代码,设计一个将两个一维数组中同下标元素求和保存到第三个数组中的函数模板。而对两个字符串求和则要求实现两个字符串的连接并保存到第三个字符串中。编程实现上述功能并使程序正确运行。说明:若

int x[3] = { 2,4,6 };int y[3] = { 1,2,3};

x和y求和保存到z,则:z[3] = { 3,6,9 };

char c[]=“abc”,d[]=“xy”;

c和d求和保存到str,str中就是“abcxy”。

/*理解主函数代码,设计一个将两个一维数组中同下标元素求和保存到第三个数组中的函数模板。而对两个字符串求和则要求实现两个字符串的连接并保存到第三个字符串中。编程实现上述功能并使程序正确运行。说明:若
int x[3] = { 2,4,6 };int y[3] = { 1,2,3};
x和y求和保存到z,则:z[3] = { 3,6,9 };
char c[]=“abc”,d[]=“xy”;
c和d求和保存到str,str中就是“abcxy”。*/
#include <iostream>
#include <cstring>
using namespace std;
template<typename T, int N>
void Add(T x[], T y[], T z[]) {
    for (int i = 0; i < N; i++) {
        z[i] = x[i] + y[i];
    }
}
template<typename T>
void Add(T c[], T d[], T str[]) {
   
       strcat(c, d);
       strcpy(str, c);
}
int  main()
{
        const  int  N  =  5;
        int  x[N]  =  {  2,-4,6,8,0},y[N],  z[N]  =  {0};
        char  c[]  =  "Hello,",  d[100]  ;
        for  (int  i(0);  i  <  N;  i++)
                cin  >>  *(y  +  i);
        while  (cin.get()  !=  '\n');
        cin.getline(d,  100);
        Add<int,  N>(x,  y,  z);
        for  (int  i(0);  i  <  N;  i++)
                cout<<z[i]<<  "  ";
        cout<<endl;
        char*  pc  =  new  char[strlen(c)  +  strlen(d)  +  1];
        Add(c,  d,  pc);
        cout  <<  pc  <<  endl;
        delete[]pc;
        return  0;
}
#include <iostream>
#include <cstring>
using namespace std;
template<typename T, int N>
void Add(T x[], T y[], T z[]) {
    for (int i = 0; i < N; i++) {
        z[i] = x[i] + y[i];
    }
}
template<typename T>
void Add(T c[], T d[], T str[]) {
    strcpy(str, c);
    strcat(str, d);
       
}
int  main()
{
        const  int  N  =  5;
        int  x[N]  =  {  2,-4,6,8,0},y[N],  z[N]  =  {0};
        char  c[]  =  "Hello,",  d[100]  ;
        for  (int  i(0);  i  <  N;  i++)
                cin  >>  *(y  +  i);
        while  (cin.get()  !=  '\n');
        cin.getline(d,  100);
        Add<int,  N>(x,  y,  z);
        for  (int  i(0);  i  <  N;  i++)
                cout<<z[i]<<  "  ";
        cout<<endl;
        char*  pc  =  new  char[strlen(c)  +  strlen(d)  +  1];
        Add(c,  d,  pc);
        cout  <<  pc  <<  endl;
        delete[]pc;
        return  0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值