2次方程式の解法

引数により与えられたパラメータにより2次方程式を規定し、その方程式の解法を得るプログラムです。

2次方程式の解法(list_54.c)
//-----------------------------------------------------------------
// seceq.c:
//      2次方程式の解法
//-----------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char *argv[])
{
    double a,b,c,root,kai1,kai2;
    if(argc<4) return 0;
    a=atof(argv[1]); b=atof(argv[2]); c=atof(argv[3]);
    printf("** The solution of a secondary equation:\n");
    // 2次方程式の解法
    if (a==0){
        printf("a is 0\n");
    } else {
        printf("\nEQUATION: %0.2lf*x^2 + %0.2lf*x + %0.2lf = 0\n",a,b,c);
        root = b*b - 4*a*c;
        if(root<0){
            kai1 = -b / (2*a);
            kai2 = sqrt(-root) / (2*a);
            printf("\tx1 = %0.2lf+%0.2lfi, x2 = %0.2lf-%0.2lfi\n",
                   kai1,kai2,kai1,kai2);
        } else {
            kai1 = (-b+sqrt(root)) / (2*a);
            kai2 = (-b-sqrt(root)) / (2*a);
            printf("\tx1 = %0.2lf, x2 = %0.2lf\n",kai1,kai2);
        }
    }
}
Gami[189]% list_54.exe 3.0 4.2 0.5
** The solution of a secondary equation:

EQUATION: 3.00*x^2 + 4.20*x + 0.50 = 0
        x1 = -0.13, x2 = -1.27
Gami[190]% list_54.exe 3.0 3.0 3.0
** The solution of a secondary equation:

EQUATION: 3.00*x^2 + 3.00*x + 3.00 = 0
        x1 = -0.50+0.87i, x2 = -0.50-0.87i   → 複素解
Gami[191]%
inserted by FC2 system