我试图使用以下代码计算2个多项式的最大公约数:
void Print(char c, int d, double* A) {
int i;
for (i = 0; i < d + 1; i++)
cout << c << "[" << i << "]= " << A[i] << endl;
cout << "Degree of " << c << ": " << d << endl << endl;
}
double* dividePolynomials(double* pol, double* div,int n,int m,int& count){
double *N,*D,*d, *q, *r;
int dN, dD, dd, dq, dr;
int i;
dN = n;
dD = m;
dq = dN - dD;
dr = dN - dD;
N = new double[n + 1];
D = new double[n + 1];
for (int i = 0; i <= n; i++)
N[i] = pol[i];
for (int i = 0; i <= dD; i++)
D[i] = div[i];
d = new double[dN + 1];
for (i = dD + 1; i < dN + 1; i++) {
D[i] = 0;
}
q = new double[dq + 1];
for (i = 0; i < dq + 1; i++) {
q[i] = 0;
}
r = new double[dr + 1];
for (i = 0; i < dr + 1; i++) {
r[i] = 0;
}
if (dD < 0) {
cout << "Degree of D is less than zero. Error!";
}
cout << "-- Procedure --" << endl << endl;
if (dN >= dD) {
while (dN >= dD) {
// d equals D shifted right
for (i = 0; i < dN + 1; i++) {
d[i] = 0;
}
for (i = 0; i < dD + 1; i++) {
d[i + dN - dD] = D[i];
}
dd = dN;
Print('d', dd, d);
// calculating one element of q
q[dN - dD] = N[dN] / d[dd];
Print('q', dq, q);
// d equals d * q[dN-dD]
for (i = 0; i < dd + 1; i++) {
d[i] = d[i] * q[dN - dD];
}
Print('d', dd, d);
// N equals N - d
for (i = 0; i < dN + 1; i++) {
N[i] = N[i] - d[i];
}
dN--;
Print('N', dN, N);
cout << "-----------------------" << endl << endl;
}
}
// r equals N
for (i = 0; i < dN + 1; i++) {
r[i] = N[i];
}
dr = dN;
cout << "=========================" << endl << endl;
cout << "-- Result --" << endl << endl;
Print('q', dq, q);
Print('r', dr, r);
count = dr;
/*delete[] N;
delete[] D;
delete[] d;
delete[] r;*/
return r;
}
double* euclid_gcd_recur(double* m, double* n, int dega, int degb)
{
int deg;
double* temp;
temp=dividePolynomials(m, n, dega, degb, deg);
if (n == 0)
return m;
return euclid_gcd_recur(n,temp,degb,deg);
}
int main() {
int n, a;
cout << "Enter the degree of the first polynomial" << endl;
cin >> n;
double* poly = new double[n+1];
cout << "Enter the coefficients of polynomial N:" << endl;
for (int i = 0; i < n + 1; i++) {
cout << "N[" << i << "]= " << endl;
cin >> poly[i];
};
cout << "Enter the degree of the second polynomial" << endl;
cin >> a;
double* poly1 = new double[a + 1];
cout << "Enter the coefficients of polynomial M:" << endl;
for (int i = 0; i < a + 1; i++) {
cout << "M[" << i << "]= " << endl;
cin >> poly1[i];
};
double* t;
t=euclid_gcd_recur(poly, poly1, n, a);
system("pause");
return 0;
}
当我尝试编译此程序时,出现以下错误:
答案 0 :(得分:0)
你有:
D = new double[n + 1];
for (int i = 0; i <= dD; i++)
D[i] = div[i];
不清楚n
和dD
之间的关系是什么。
您需要将第一行更改为:
D = new double[dD + 1]; // Use dD, not n
或将循环更改为:
for (int i = 0; i <= n; i++) // Use n, not dD.
D[i] = div[i];
我不清楚哪一个应该改变。