#include #include #include #include #include #define INPUT_FILE "data.txt" #define OUTPUT_FILE "rezult.txt" int CorrectCoefficients(char* buffer) { int count = 1, correct = 1; FILE* data_rezult = fopen(OUTPUT_FILE, "w+"); for (int i = 0; i < strlen(buffer); i++) { if (buffer[i] == ' ') { count++; } } for (int i = 0; i < strlen(buffer); i++) { if (((buffer[i] < '0') || (buffer[i] > '9')) && (buffer[i] != ' ') && (buffer[i] != '.')) { fprintf(data_rezult, "coefficients can't be a symbol"); printf("coefficients can't be a symbol"); correct = 0; } } if ((count < 3)&&(correct==1)) { fprintf(data_rezult, "not enough coefficients"); printf("not enough coefficients"); correct = 0; } else if ((count > 3) && (correct == 1)) { fprintf(data_rezult, "too many coefficients"); printf("too many coefficients"); correct = 0; } return correct; } int x(double k[3]) { FILE* data_rezult = fopen(OUTPUT_FILE, "w+"); printf("%.3f*x^2+(%.3f*x)+(%.3f)", k[0], k[1], k[2]); double d = pow(k[1], 2) - 4. * k[0] * k[2]; printf("\nD = %.3f", d); fprintf(data_rezult, "D: %f", d); if (d < 0) { printf("\nvalid roots don't exist"); fprintf(data_rezult, "\nvalid roots don't exist"); return 1; } double x1 = (-k[1] + sqrt(d)) / (2 * k[0]); double x2 = (-k[1] - sqrt(d)) / (2 * k[0]); if (x1 == x2) { printf("\nx = %.3f", x1); fprintf(data_rezult, "\nx = %f", x1); return 0; } printf("\nx1 = %.3f\nx2 = %.3f", x1, x2); fprintf(data_rezult, "\nx1 = %f\nx2 = %f", x1, x2); } int main() { char buffer[128]; double k[3]; FILE* data_open = fopen(INPUT_FILE, "r"); FILE* data_rezult = fopen(OUTPUT_FILE, "w+"); if (data_open == 0) { printf("Can't open file"); return 1; } fgets(buffer, 127, data_open); if (CorrectCoefficients(buffer)) { k[0] = atof(strtok(buffer, " ")); for (int i = 1; i < 3; i++) { k[i] = atof(strtok(NULL, " ")); } int count = 0; for (int i = 0; i < 3; i++) { if (k[i] == 0) { count++; } } if (count == 3) { fprintf(data_rezult, "all coefficients can't be null"); printf("all coefficients can't be null"); return 1; } x(k); } }