Consider the definitions and prototypes below #include struct Term size_t degree
ID: 3871685 • Letter: C
Question
Consider the definitions and prototypes below #include struct Term size_t degree; double coefficient; using namespace std; list random_polynomial ( size_t nbr // Returns a list of random terms, with as many terms as the value of nbr // The coefficients are uniformly distributed in the interval [o.0, 1.0 // and the degrees are random integers from 0 to 9. void write_polynomial list poly); // Writes the terms in the polynonial poly, using the symbol // for the variable in the polynomial. The coefficients are written // in scientific notation with 4 decimal places accuracy, e.g.: // + 1 . 3154e-01+x"7 + 4.5865e-01*x"3 + 2.1896e-01#x^0 + 6.7886e-01*x^4 Write the definitions of the functions random.polynomial and write.polynomial.Explanation / Answer
#include<iostream>
#include<stdlib.h>
#include<list>
#include<time.h>
#include<iomanip>
struct Term
{
size_t degree;
double coefficient;
};
using namespace std;
list<Term> random_polynomial(size_t nbr){
list<Term> poly;
Term t;
//t = new Term();
double dt = (double)1/nbr;
srand(time(NULL));
for (int i = 0; i<nbr; i++){
double d = i+1;
t.degree = rand()%10;;
t.coefficient = dt * d;
poly.push_back(t);
}
return poly;
}
void write_polynomial(list<Term> poly){
std::list<Term>::iterator ptr;
for (ptr = poly.begin(); ptr != poly.end(); ptr++){
cout << " +" << std::scientific << setprecision(4) << (*ptr).coefficient;
cout << "x^" << (*ptr).degree ;
}
cout << endl;
}
int main(){
list<Term> p;
p = random_polynomial(7);
write_polynomial(p);
}