// // 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 /* Not necessary in this example */ void computeDerivative(double *a, int n); int main() { // Open the input file FILE* f = fopen("input.txt", "rt"); if (f == NULL) { perror("Cannot open the input file"); return -1; } // Read the size of array int n; if ((fscanf(f, "%d", &n) < 1) || n <= 0) { printf("Illegal input file.\n"); fclose(f); 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 (fscanf(f, "%lg", a + i) < 1) { printf("Incorrect format of input file.\n"); fclose(f); delete[] a; return -1; } } fclose(f); computeDerivative(a, n); // Open the output file FILE* h = fopen("output.txt", "wt"); if (h == NULL) { perror("Cannot open the output file"); return -1; } if (n <= 1) { // Zero derivative fprintf(h, "0\n"); } else { for (int i = 0; i < n-1; ++i) { if (i > 0) { fprintf(h, " "); // Write a separator } fprintf(h, "%g", a[i]); } fprintf(h, "\n"); // Write end of line } fclose(h); 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; } }