gpt4 book ai didi

c++ - 以二维项数组作为数据成员并使用运算符+重载的多项式类

转载 作者:行者123 更新时间:2023-11-28 07:33:39 25 4
gpt4 key购买 nike

实现了一个多项式类,其中包含二维项数组和项数作为数据成员。数组行是系数,数组列是指数。我们的目标是重载 + 运算符来进行加法,即如果指数相同则添加系数,否则按原样包含项。

输出部分正确,输出的最后一项不正确..请查看运算符+重载并提出补救措施!提前致谢...

查看评论以消除以前的缺陷。

#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H

#include <iostream>
using namespace std;
#define MAX 10

class Polynomial {
public :
Polynomial ();
//~Polynomial(){ delete [] terms[MAX]; } (see comments)
void enterTerms();
Polynomial operator +(const Polynomial & );
private :
int terms[MAX][2]; //define size statically if not using "new"
int n; //number of terms
};
#endif

#include "polynomial.h"


Polynomial Polynomial :: operator + ( const Polynomial & p ){
Polynomial temp, sum;
temp.n = n + p.n;
int common = 0;
//first write sum as concatenation of p1 and p2
for ( int i = 0 ; i < n ; i++ ){
temp.terms[i][0] = terms[i][0];
temp.terms[i][1] = terms[i][1];
}
//notice j and k for traversing second half of sum, and whole p2 resp
for ( int j = n, k = 0; j < n + p.n, k < p.n ; j++, k++ ){
temp.terms[j][0] = p.terms[k][0];
temp.terms[j][1] = p.terms[k][1];
}
for ( int l = 0; l < temp.n - 1 ; l++ ){ // 0 to 1 less than length
for ( int m = l + 1 ; m < temp.n ; m++ ){ // 1 more than l to length,so that compared pairs are non redundant
if( temp.terms[l][1] == temp.terms[m][1] ){
common++; //common terms reduce no. of terms
temp.terms[l][0] += temp.terms[m][0]; //coefficients added of exponents same
temp.terms[m][0] = 0;
}
}
}
sum.n = temp.n - common;
for ( int q = 0, r = 0; q < temp.n, r < sum.n; q++, r++){
if ( temp.terms[q][0] == 0 )
continue;
else if ( temp.terms[q][0] != 0 ){
sum.terms[r][0] = temp.terms[q][0];
sum.terms[r][1] = temp.terms[q][1];
}
}
cout << sum;
return sum;
}

Polynomial :: Polynomial(){
for ( int i = 0; i < MAX; i++ ){
terms[i][0] = 0;
terms[i][1] = 0;
}
}
void Polynomial :: enterTerms(){
int num;
cout<<"enter number of terms in polynomial\n";
cin >> num;
n = num >= 0 ? num : 1;
cout << "enter coefficient followed by exponent for each term in polynomial\n";
for ( int i = 0; i < n ; i++)
cin >> terms[i][0] >> terms[i][1] ;
}
int main(){
Polynomial p1 , p2;
p1.enterTerms();
p2.enterTerms();
p1 + p2;
system("PAUSE");
return EXIT_SUCCESS;
}

op

最佳答案

用最大元素声明你的数组:

private :
int terms[MAX][2];

关于c++ - 以二维项数组作为数据成员并使用运算符+重载的多项式类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17167467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com