// // File "input.txt" contains a polynomial: // first the number of its coefficients, then // the coefficients in descending order. // For example, for the polynomial // 3*x^3 + 5^x^2 - 7^x + 1 // the file "input.txt" contains: // 4 // 3 5 -7 1 // // The program must write the coefficients of // the derivative of this polynomial in descending order // into the file "output.txt". // In this example, the derivative of the polynomial is // 9*x^2 + 10*x - 7, // so the file "output.txt" should contain // 9 10 -7 // // The program should use the same array for the // coefficients of polynomial (input data) and // the resulting coefficient of derivative (output data). // #include #include #include /* for strerror(errno) */ #include /* Not necessary in this example */ using namespace std; void computeDerivative(double *a, int n); int main() { // Open the input file ifstream f("input.txt"); if (!f.is_open()) { cerr << "Cannot open the input file: " << strerror(errno) << endl; return -1; } // Read the size of array int n; if (!(f >> n) || n <= 0) { cerr << "Illegal input file." << endl; f.close(); return -1; } // Allocate an array in dynamic memory double *a = new double[n]; // Read coefficients of a polynomial for (int i = 0; i < n; ++i) { if (!(f >> a[i])) { cerr << "Incorrect format of input file." << endl; f.close(); delete[] a; return -1; } } f.close(); computeDerivative(a, n); // Open the output file ofstream g("output.txt"); if (!g.is_open()) { cerr << "Cannot open the output file: " << strerror(errno) << endl; delete[] a; return -1; } // Write results to both the output file and the console if (n <= 1) { // Zero derivative g << 0 << endl; cout << 0 << endl; } else { for (int i = 0; i < n-1; ++i) { if (i > 0) { g << ' '; // Write a separator cout << ' '; } g << a[i]; cout << a[i]; } g << endl; cout << endl; } g.close(); delete[] a; return 0; // Success! } void computeDerivative(double *a, int n) { int deg = n - 1; // Degree of a term int i = 0; // Index of the term coefficient in array while (deg > 0) { a[i] *= deg; --deg; ++i; } }