fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void readPolynom(int **p, int *n) {
  5. printf("Give the degree of the polynom -> ");
  6. scanf("%d", n);
  7.  
  8. // Allocate memory for coefficients (degree + 1 elements)
  9. *p = (int *)malloc((*n + 1) * sizeof(int));
  10. if (*p == NULL) {
  11. printf("Memory allocation failed!\n");
  12. exit(1);
  13. }
  14.  
  15. for(int i = 0; i <= *n; i++) {
  16. printf("P[%d] = ", i);
  17. scanf("%d", (*p + i));
  18. }
  19. }
  20.  
  21. void writePolynom(int *p, int *n) {
  22. printf("p(x) = %dx^0", p[0]);
  23. for(int i = 1; i <= *n; i++) {
  24. printf(" + %dx^%d", p[i], i);
  25. }
  26. }
  27.  
  28. float valuePolynom(int *p, int *n, float x) {
  29. float value = p[0],
  30. aux = 1;
  31.  
  32. for(int i = 1; i <= *n; ++i) {
  33. aux = aux * x;
  34. value += aux * p[i];
  35. }
  36.  
  37. return value;
  38. }
  39.  
  40. void derivatePolynom(int *p, int *n) {
  41. for(int i = 0; i < *n; i++) {
  42. p[i] = p[i + 1] * (i + 1);
  43. }
  44. (*n)--;
  45. }
  46.  
  47. int main(int argc, char const *argv[]) {
  48. int *coef = NULL; // Dynamic array for coefficients
  49. int n; // Degree
  50.  
  51. readPolynom(&coef, &n);
  52. writePolynom(coef, &n);
  53. derivatePolynom(coef, &n);
  54. printf("\n\n");
  55. writePolynom(coef, &n);
  56.  
  57. float x = 1.450;
  58. float ans = valuePolynom(coef, &n, x);
  59. printf("\np(%.3f) = %.3f\n", x, ans);
  60.  
  61. // Free allocated memory
  62. free(coef);
  63. return 0;
  64. }
Success #stdin #stdout 0s 5284KB
stdin
3
2 3 4
stdout
Give the degree of the polynom -> P[0] = P[1] = P[2] = P[3] = p(x) = 2x^0 + 3x^1 + 4x^2 + 0x^3

p(x) = 3x^0 + 8x^1 + 0x^2
p(1.450) = 14.600