已知文件Coefficient. txt中存有多个方程 ax²+bx+c=0 中系数 a,b,c的值,数据按行排列,编写程序求出方程的解,并将结果写入到 result. txt文件中,要求考虑 a,b,c 各种取值情况。 Coefficient. txt内容举例:
0 2 6 0 0 0 1 1 8
#include <stdio.h> #include <math.h> int main() { FILE *inputFile = fopen("Coefficient.txt", "r"); FILE *outputFile = fopen("result.txt", "w"); if (inputFile == NULL || outputFile == NULL) { printf("无法打开文件。\n"); return 1; } double a, b, c; while (fscanf(inputFile, "%lf %lf %lf", &a, &b, &c) == 3) { double discriminant = b * b - 4 * a * c; double root1, root2; if (a == 0) { if (b == 0) { if (c == 0) { fprintf(outputFile, "无穷多解\n"); } else { fprintf(outputFile, "无解\n"); } } else { fprintf(outputFile, "线性方程解:x = %.2lf\n", -c / b); } } else if (discriminant > 0) { root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); fprintf(outputFile, "两个实根:x1 = %.2lf, x2 = %.2lf\n", root1, root2); } else if (discriminant == 0) { root1 = -b / (2 * a); fprintf(outputFile, "重根:x = %.2lf\n", root1); } else { double realPart = -b / (2 * a); double imaginaryPart = sqrt(-discriminant) / (2 * a); fprintf(outputFile, "两个复根:x1 = %.2lf + %.2lfi, x2 = %.2lf - %.2lfi\n", realPart, imaginaryPart, realPart, imaginaryPart); } } fclose(inputFile); fclose(outputFile); printf("计算完成,结果已保存到result.txt文件中。\n"); return 0; }