【解決方法】C++ での OOP 多項式プログラミング

プログラミングQA


こんにちは、すべてのヘッダー (hpp)、cpp を含む C++ の多項式に関する課題 (2011 年 9 月 26 日期限) を提出する必要があります。メイン ファイルはすでに指定されており、以下で見つけることができます。

C++
/*
  Polynomial_s.cpp
 
  Syntax checking of the interface of a Polynomial class

  
*/

#include "Polynomial.hpp"
#include <iostream>
#include <cassert>
#include <vector>

int main() {

  Polynomial q;
  Polynomial q2 = q;
  Polynomial q3(q);

  q2 = q;

  // constant constructor
  Polynomial c(5);

  // output
  std::cout << c << '\n';

  // equality
  c == c;

  // inequality
  c != c;

  // addition
  Polynomial a1(2);
  Polynomial a2(3);
  Polynomial a3(5);

  a1 += a2;

  assert(a1 == a3);
  assert(a1 == 5);

  // access coefficients based on degree of term
  a3.coefficient(0);

  // linear constructor
  Polynomial l(2, -3);
  assert(l.coefficient(0) == 2);
  assert(l.coefficient(1) == -3);

  // quadratic constructor
  Polynomial quad(1, 0, -1);
  assert(quad.coefficient(0) == 1);
  assert(quad.coefficient(1) == 0);
  assert(quad.coefficient(2) == -1);

  // vector constructor
  std::vector<double> coeffs(4);
  coeffs[0] = 1; coeffs[1] = 0; coeffs[2] = -1;
  Polynomial poly(coeffs);

  // c-array constructor
  double acoeffs[] = { 1, 0, -1 };
  Polynomial polya(acoeffs, 3);

  // factoring
  std::vector<polynomial> factors = polya.factor();

  return 0;
}

解決策 2

よく考えてみると、推測ですが、あなたは、誰かが自分に代わってこのクラスの実装を書いてくれるので、明日それをすべて自分の仕事だと主張して教授に渡すことができると期待しているのでしょう。 申し訳ありませんが、それは起こりません。 この課題を完了するために週末を 1 回しか残せない状況にどのようにして陥ったのかを自問する必要があります。 おそらく、あまりにも多くの時間を費やしたからでしょう これ[^]。

解決策 3

C++

#include
#include

名前空間 std を使用します。

クラス多項式 {
プライベート:
整数度;
int* 係数;

公共:
多項式(int deg, int* coeffs) : 度(deg), 係数(coeffs) {}

~多項式() {
消去[] 係数;
}

void printPolynomial() const {
for (int i = 度; i >= 0; i–) {
if (係数[i] != 0) {
if (i == 度)
cout << 係数[i] << "x^" << i;
それ以外 {
cout << " ";
if (係数[i] > 0)
cout << "+";
cout << 係数[i] << "x^" << i;
}
}
}
cout << endl;
}
};

int main() {
int 次数 = 4;
int* coeffs = 新しい int[degree + 1];
係数[0] = 5;
係数[1] = 0;
係数[2] = 2;
係数[3] = -1;
係数[4] = 3;

多項式poly(degree, coeffs);

cout << "多項式: ";
Poly.printPolynomial();

消去[] 係数;

0を返します。
}

コメント

タイトルとURLをコピーしました