/* 2nd_eq.c Function: 虚数解まで広げて2次方程式の解を求める Author: Ken Date: 02/07/12 URL: http://blue.ribbon.to/~kenweb/ mail: kenweb@s8.xrea.com */ #include <stdio.h> #include <math.h> double calc_a_b_c(float a,float b,float c); int main(int argc, char *argv[]) { float a,b,c; /*変数宣言*/ fprintf(stdout,"2次方程式の解の計算\n\n"); /*方程式の係数入力*/ fprintf(stdout,"ax^2 + bx + c = 0\n\n"); fprintf(stdout,"aの値を入力してください\n"); fscanf(stdin,"%f",&a); fprintf(stdout,"bの値を入力してください\n"); fscanf(stdin,"%f",&b); fprintf(stdout,"cの値を入力してください\n"); fscanf(stdin,"%f",&c); calc_a_b_c(a,b,c); } double calc_a_b_c(float a,float b,float c) /*解の計算*/ { double r,l,x1,x2,x,d; if (a==0) /*一次方程式になった場合*/ { x=-c/b; fprintf(stdout,"%fx + %f = 0\n",b,c); fprintf(stdout,"x=%f\n\n",x); return(0); } fprintf(stdout,"%fx^2 + %fx + %f = 0\n",a,b,c); d=pow((double)b,2.0)-4*a*c; /*解の判別式*/ if (d<0) /*虚数解を持つとき*/ { fprintf(stdout,"異なる2つの虚数解を持つ ( i^2 = -1 )\n"); d=-d; r=-b/(2*a); l=sqrt((double)d)/(2.0*a); fprintf(stdout,"x1 = %f ",r); if (l>=0) fprintf(stdout,"+%f i\n",l); else fprintf(stdout,"%f i\n",l); fprintf(stdout,"x2 = %f ",r); if (l>=0) fprintf(stdout,"-%f i\n",l); else fprintf(stdout,"+%f i\n",-l); } else if (d==0) /*重解を持つとき*/ { x=-b/(2*a); fprintf(stdout,"x = %f(重解)\n\n",x); } else if (d>0) /*2つの実数解を持つとき*/ { x1=(-b+sqrt((double)d))/(2.0*a); x2=(-b-sqrt((double)d))/(2.0*a); fprintf(stdout,"異なる2つの実数解を持つ\n"); fprintf(stdout,"x1 = %f\n",x1); fprintf(stdout,"x2 = %f\n\n",x2); } return(0); }