workwithfiles.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <stdio.h>
  2. #include <locale.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <math.h>
  6. #define INPUT_FILE "data.txt"
  7. #define OUTPUT_FILE "rezult.txt"
  8. int CorrectCoefficients(char* buffer) {
  9. int count = 1, correct = 1;
  10. FILE* data_rezult = fopen(OUTPUT_FILE, "w+");
  11. for (int i = 0; i < strlen(buffer); i++) {
  12. if (buffer[i] == ' ') {
  13. count++;
  14. }
  15. }
  16. for (int i = 0; i < strlen(buffer); i++) {
  17. if (((buffer[i] < '0') || (buffer[i] > '9')) && (buffer[i] != ' ') && (buffer[i] != '.')) {
  18. fprintf(data_rezult, "coefficients can't be a symbol");
  19. printf("coefficients can't be a symbol");
  20. correct = 0;
  21. }
  22. }
  23. if ((count < 3)&&(correct==1)) {
  24. fprintf(data_rezult, "not enough coefficients");
  25. printf("not enough coefficients");
  26. correct = 0;
  27. }
  28. else if ((count > 3) && (correct == 1)) {
  29. fprintf(data_rezult, "too many coefficients");
  30. printf("too many coefficients");
  31. correct = 0;
  32. }
  33. return correct;
  34. }
  35. int x(double k[3]) {
  36. FILE* data_rezult = fopen(OUTPUT_FILE, "w+");
  37. printf("%.3f*x^2+(%.3f*x)+(%.3f)", k[0], k[1], k[2]);
  38. double d = pow(k[1], 2) - 4. * k[0] * k[2];
  39. printf("\nD = %.3f", d);
  40. fprintf(data_rezult, "D: %f", d);
  41. if (d < 0) {
  42. printf("\nvalid roots don't exist");
  43. fprintf(data_rezult, "\nvalid roots don't exist");
  44. return 1;
  45. }
  46. double x1 = (-k[1] + sqrt(d)) / (2 * k[0]);
  47. double x2 = (-k[1] - sqrt(d)) / (2 * k[0]);
  48. if (x1 == x2) {
  49. printf("\nx = %.3f", x1);
  50. fprintf(data_rezult, "\nx = %f", x1);
  51. return 0;
  52. }
  53. printf("\nx1 = %.3f\nx2 = %.3f", x1, x2);
  54. fprintf(data_rezult, "\nx1 = %f\nx2 = %f", x1, x2);
  55. }
  56. int main()
  57. {
  58. char buffer[128];
  59. double k[3];
  60. FILE* data_open = fopen(INPUT_FILE, "r");
  61. FILE* data_rezult = fopen(OUTPUT_FILE, "w+");
  62. if (data_open == 0) {
  63. printf("Can't open file");
  64. return 1;
  65. }
  66. fgets(buffer, 127, data_open);
  67. if (CorrectCoefficients(buffer)) {
  68. k[0] = atof(strtok(buffer, " "));
  69. for (int i = 1; i < 3; i++) {
  70. k[i] = atof(strtok(NULL, " "));
  71. }
  72. int count = 0;
  73. for (int i = 0; i < 3; i++) {
  74. if (k[i] == 0) {
  75. count++;
  76. }
  77. }
  78. if (count == 3) {
  79. fprintf(data_rezult, "all coefficients can't be null");
  80. printf("all coefficients can't be null");
  81. return 1;
  82. }
  83. x(k);
  84. }
  85. }