Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<vector>
- #ifndef Poly
- #define Poly
- using namespace std;
- class poly {
- private:
- vector <double> tab;
- public:
- friend ostream& operator<<(ostream&, poly);
- friend poly operator+(poly p1, poly p2);
- friend poly operator*(poly p1, poly p2);
- double operator()(double x);
- double& operator[](int x);
- poly(double x = 0) {
- tab.push_back(x);
- }
- };
- #endif
- #include <iostream>
- #include<cmath>
- #include "poly.h"
- using namespace std;
- double poly::operator()(double x) {
- double res=0;
- unsigned int power=0;
- int i;
- for(i=0;i<tab.size();i++){
- res+=tab[i]*pow(x,power);
- power++;
- }
- return res;
- }
- double& poly::operator[](int x) {
- if (tab.size() < x) tab.resize(x+1 ,0);
- return tab[x];
- }
- poly operator+(poly p1,poly p2){
- poly tmp;
- (p1.tab.size() > p2.tab.size()) ? tmp.tab.resize(p1.tab.size(), 0) : tmp.tab.resize(p2.tab.size(),0);
- int i;
- for (i = 0;i < tmp.tab.size();i++) {
- if (p1.tab.size() > i&&p2.tab.size() > i)tmp[i] = p1[i] + p2[i];
- else if (p1.tab.size() > i&&p2.tab.size() <= i)tmp[i] = p1[i];
- else tmp[i] = p2[i];
- }
- return tmp;
- }
- poly operator*(poly p1, poly p2){
- poly tmp;
- tmp.tab.resize(p1.tab.size() + p2.tab.size(), 0);
- int i,j;
- for (i = 0;i < p1.tab.size();i++) {
- if (p1[i] != 0) {
- for (j = 0;j < p2.tab.size();j++) {
- tmp[i + j] += p1[i] * p2[j];
- }
- }
- }
- return tmp;
- }
- ostream& operator<<(ostream &Out, poly p2) {
- int i;
- for (i = p2.tab.size()-1;i >=0;i--) {
- if(p2[i]!=0){
- if(p2[i]!=1)Out << p2[i];
- if(i>0)Out<<"x";
- if(i>1)Out<<"^"<<i;
- if (i - 1 !=-1 && p2[i - 1] >= 0) Out << " + ";
- }
- }
- return Out;
- }
- //rule of 3 c++
- int main(void)
- {
- poly P1; //Declare object representing polynomial P1
- P1[3] = 2; P1[1] = 3.6; P1[0] = 7; //Specify coefficients of P1 = 2x^3 + 3.6x + 7
- poly P2=5; //Declare object representing polynomial P2 = 5
- P2[1] = 3; P2[2] = 6; P2[4] = 1; //Specify additional coefficients of P2 = x^4 + 6x^2 + 3x + 5
- cout << "Polynomial P1: " << P1 << endl; //Print P1
- cout << "Polynomial P2: " << P2 << endl; //Print P2
- poly P3 = P1 + P2; //Add P1 and P2
- cout << "Sum of polynomials P1 and P2: " << P3 << endl; //Print sum of P1 and P2
- P3 = P1 * P2; //Multiply P1 by P2
- cout << "Product of polynomials P1 and P2: " << P3 << endl; //Print product of P1 and P2
- P3 = 2 * P1; //Multiply P1 by 2
- cout << "Polynomial P1 multiplied by 2: " << P3 << endl; //Print product of P1 and 2
- double val = P1(3.14); //Calculate the value of P1 at point 3.14
- cout << "Value of polynomial P1 at point 3.14: " << val << endl; //Print the value of P1 at point 3.14
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement