【C语言习题】解方程ax^2+bx+c=0

题目

在这里插入图片描述

分析

  1. 读取Coefficient.txt中的值,这里格式化读取即可
  2. 将计算结果写入到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);
  1. 解方程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} b24ac )/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
Coefficient.txt
result.txt
result.txt

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值