#include <cstdlib>
#include <iostream>
#include <conio.h>
#define MAX 10
using namespace std;
class nomi{
public :
int coeff;
int exp;
};
class poly{
public :
struct nomi t [10] ;
int noofterms ;
};
void initpoly ( poly * ) ;
void polyappend ( poly *, int c, int e ) ;
struct poly polyadd ( poly, poly ) ;
void display ( poly ) ;
void initpoly ( poly *p ){
int i ;
p -> noofterms = 0 ;
for ( i = 0 ; i < MAX ; i++ ){
p -> t[i].coeff = 0 ;
p -> t[i].exp = 0 ;
}
}
/* adds the term of polynomial to the array t */
void polyappend ( poly *p, int c, int e ){
p -> t[p -> noofterms].coeff = c ;
p -> t[p -> noofterms].exp = e ;
( p -> noofterms ) ++ ;
}
/* displays the polynomial equation */
void display ( poly p ){
int flag = 0, i ;
for ( i = 0 ; i < p.noofterms ; i++ ){
if ( p.t[i].exp != 0 )
cout<<p.t[i].coeff<<" x^"<<p.t[i].exp<<" + ";
else{
cout<<p.t[i].coeff;
flag = 1 ;
}
}
if ( !flag )
cout<<"\b\b";
}
/* adds two polynomials p1 and p2 */
poly polyadd ( poly p1, poly p2 ){
int i, j, c ;
poly p3 ;
initpoly ( &p3 ) ;
if ( p1.noofterms > p2.noofterms )
c = p1.noofterms ;
else
c = p2.noofterms ;
for ( i = 0, j = 0 ; i <= c ; p3.noofterms++ ){
if ( p1.t[i].coeff == 0 && p2.t[j].coeff == 0 )
break ;
if ( p1.t[i].exp >= p2.t[j].exp ){
if ( p1.t[i].exp == p2.t[j].exp ){
p3.t[p3.noofterms].coeff = p1.t[i].coeff + p2.t[j].coeff ;
p3.t[p3.noofterms].exp = p1.t[i].exp ;
i++ ;
j++ ;
}
else{
p3.t[p3.noofterms].coeff = p1.t[i].coeff ;
p3.t[p3.noofterms].exp = p1.t[i].exp ;
i++ ;
}
}
else
{
p3.t[p3.noofterms].coeff = p2.t[j].coeff ;
p3.t[p3.noofterms].exp = p2.t[j].exp ;
j++ ;
}
}
return p3 ;
}
int main( ){
poly p1, p2, p3 ;
initpoly ( &p1 ) ;
initpoly ( &p2 ) ;
initpoly ( &p3 ) ;
polyappend ( &p1, 3, 8 ) ;
polyappend ( &p1, 2, 6 ) ;
polyappend ( &p1, 6, 5 ) ;
polyappend ( &p1, 4, 4 ) ;
polyappend ( &p1, 5, 2 ) ;
polyappend ( &p2, 3, 4 ) ;
polyappend ( &p2, 4, 3 ) ;
polyappend ( &p2, 2, 2 ) ;
polyappend ( &p2, 8, 1 ) ;
polyappend ( &p2, 1, 0 ) ;
p3 = polyadd ( p1, p2 ) ;
cout<< ( "\nFirst polynomial:\n" ) ;
display(p1) ;
cout<< ( "\n\nSecond polynomial:\n" ) ;
display ( p2 ) ;
cout<< ( "\n\nResultant polynomial:\n" ) ;
display ( p3 ) ;
getch( ) ;
}
Sabtu, 20 Oktober 2012
Penjumlahan Polinomial
Langganan:
Posting Komentar (RSS)
Komentar :
Posting Komentar