next up previous
Next: 補足 fprintf Up: 実習 2: 2次方程式の解 Previous: 実習 2: 2次方程式の解

中学校で教わったままだと...

これをそのままプログラムします. 複素数解を持つ時には, それをエラーメッセージとして 出します.

/* File name 5-2.c */

#include <stdio.h>
#include <math.h>
#define BUFFSIZE 1024

main()
{
        double a, b, c, det;
        double ans1, ans2;
        char input[BUFFSIZE];

        printf("Input the coefficients >> ");

        fgets(input, BUFFSIZE, stdin);
        sscanf(input, "%lf %lf %lf", &a, &b, &c);

        if (a==0){
                fprintf(stderr, "a=0 does not make a quadratic equation.\n");
                exit(1);
        }

        det = b*b-4*a*c;

        if (det < 0.0){
                fprintf(stderr,"The equation has imaginary roots\n");
                exit(1);
        }

        else if (det==0.0){
                printf("The root is %17.16f\n", a/2.0);
                return(0);
        }

        else{
                ans1= (-b+sqrt(det))/(2.0*a);
                ans2= (-b-sqrt(det))/(2.0*a);
                printf("The roots are %17.16f and %17.16f\n", ans1, ans2);
        }
}



Subsections

Next: 補足 fprintf Up: 実習 2: 2次方程式の解 Previous: 実習 2: 2次方程式の解