KP3.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. void PrintTable(int m);
  5. void PrintTableArguments(float x, float y, float yt, int n, int m);
  6. int FactorialNum(int num);
  7. int main(void) {
  8. int num_div = 0;
  9. float epsilon = 1.0f;
  10. float y;
  11. float yt;
  12. int n = 0;
  13. int m = 0;
  14. printf("Enter num: ");
  15. scanf("%d", &num_div);
  16. while (1.0f + (epsilon / 2) > 1.0f) {
  17. epsilon /= 2;
  18. }
  19. if (num_div > 9 && num_div < 21) {
  20. m = 2;
  21. } else if (num_div > 20 && num_div < 31) {
  22. m = 3;
  23. } else if (num_div < 100) {
  24. m = 3;
  25. } else if (num_div >= 100) {
  26. m = 4;
  27. }
  28. printf("Machine epsilon: %.8f\n", epsilon);
  29. PrintTable(m);
  30. float xy = 0.5f / num_div;
  31. float x = 0.0f;
  32. n = 1;
  33. for (int i = 0; i < num_div + 1; ++i) {
  34. y = 2 * (cos(x)*cos(x) - 1);
  35. while (fabs(yt - y) > epsilon || n == 100) {
  36. yt = yt + pow((-1), n) * pow(2 * x, 2 * n) / FactorialNum(2*n);
  37. n++;
  38. }
  39. PrintTableArguments(x, y, yt, n, m);
  40. x += xy;
  41. yt = 0.f;
  42. n = 1;
  43. }
  44. return 0;
  45. }
  46. void PrintTable(int m) {
  47. printf("+%s+-----------------------+-------------+-----+\n", (m + 2) == 4 ? "----" : ((m + 2) == 5 ? "-----" : "------"));
  48. printf("|%*c%*c|%22s%1c|%10s%3c|%3c%2c|\n", (m+2) % 2 ? (m + 2) / 2 + 1 : (m + 2) / 2, 'x', (m + 2) / 2, ' ', "y = 2(cos(x) ^ 2 - 1)", ' ', "tayler", ' ', 'n', ' ');
  49. printf("+%s+-----------------------+-------------+-----+\n", (m + 2) == 4 ? "----" : ((m + 2) == 5 ? "-----" : "------"));
  50. }
  51. void PrintTableArguments(float x, float y, float yt, int n, int m) {
  52. printf("|%3.*f|%6c%+-.8f%6c|%1c%+8.8f%1c|%3d%2c|\n", m, x, y, ' ', ' ', ' ', yt, ' ', n, ' ');
  53. printf("+%s+-----------------------+-------------+-----+\n", (m + 2) == 4 ? "----" : ((m + 2) == 5 ? "-----" : "------"));
  54. }
  55. int FactorialNum(int num) {
  56. int n = 1;
  57. for (int i = 1; i <= num; ++i) {
  58. n *= i;
  59. }
  60. return n;
  61. }