题目
分析
- 读取Coefficient.txt中的值,这里格式化读取即可
- 将计算结果写入到result.txt 中
对文件的读写操作:
FILE *out,*in;
if((out = fopen("Coefficient.txt","r")) == NULL){
printf("can't open file!\n");
exit(0);
}
if((in = fopen("result.txt","w")) == NULL){
printf("can't open file!\n");
exit(0);
}
while (!feof(out)) {
fscanf(out, "%lf%lf%lf", &a, &b, &c);
fprintf(in,"方程%gx^2+%gx+%g=0: ",a,b,c);
}
fclose(out);
fclose(in);
- 解方程ax2+bx+c=0,并考虑a,b,c的各种取值
首先要理清方程的所有可能性:
1)a=0,不是二次方程
2)b2-4ac=0,有两个相等实数根。
3)b2-4ac>0,有两个不等实数根。
4)b2-4ac<0,有两个共轭复跟。应当以p+qi和p-qi的形式输出复根。其中,p=-b/2a,q=( b 2 − 4 a c \sqrt{b^2-4ac} b2−4ac)/2a。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void jie(double a, double b, double c,FILE *in){
double disc,x1,x2,realpart,imagpart;
if(fabs(a) <= 1e-6) //a为0时,一元方程
if(b == 0) //b也为0时
if(c == 0)
fprintf(in,"无穷个解\n"); //a,b,c为0时,无穷多解
else
fprintf(in,"无解\n"); //a,b为0,c不为0,无解
else
fprintf(in,"x = %g\n",-c/b); //一次方程的解
else { //a不为0时
disc = b * b - 4 * a * c;
if(fabs(disc) <= 1e-6)
fprintf(in,"两个相同解x1=x2=%g\n",-b/(2*a));
else if(disc>1e-6){
x1 = (-b+sqrt(disc))/(2*a);
x2 = (-b-sqrt(disc))/(2*a);
fprintf(in,"两个不同的实根:%8.4g 和%8.4g\n",x1,x2);
} else{
realpart = -b/(2*a);
imagpart = sqrt(-disc)/(2*a);
fprintf(in,"两个共轭复根:");
fprintf(in,"%8.4g+%gi",realpart,imagpart);
fprintf(in," 和");
fprintf(in,"%8.4g-%gi\n",realpart,imagpart);
}
}
}
int main() {
double a,b,c;
FILE *out,*in;
if((out = fopen("Coefficient.txt","r")) == NULL){
printf("can't open file!\n");
exit(0);
}
if((in = fopen("result.txt","w")) == NULL){
printf("can't open file!\n");
exit(0);
}
while (!feof(out)) {
fscanf(out, "%lf%lf%lf", &a, &b, &c);
fprintf(in,"方程%gx^2+%gx+%g=0: ",a,b,c);
jie(a,b,c,in);
}
fclose(out);
fclose(in);
return 0;
}
结果示例
Coefficient.txt
result.txt