C语言 对负数开根号

来源:百度知道 编辑:UC知道 时间:2024/07/04 19:19:02
题目:求方程ax^2+bx+c=0的根,用3个函数分别求当b^2-4ac大于零,等于零和小于零时的根,并输出结果。

我目前遇到的困难:在void C部分,b^2-4ac<0,sqrt不能运算,但是老师要求运算出复数.....

#include<stdio.h>
#include<math.h>
void main()
{
void A(float a,float b,float c);
void B(float a,float b,float c);
void C(float a,float b,float c);
float a,b,c,d;
scanf("%f,%f,%f",&a,&b,&c);
d=b*b-4*a*c;
if(d>0) A(a,b,c);
if(d==0) B(a,b,c);
if(d<0) C(a,b,c);
getch();
}

void A(float a,float b,float c)
{
float x1,x2;
x1=(-b+sqrt(b*b-4*a*c))/(2*a);
x2=(-b-sqrt(b*b-4*a*c))/(2*a);
printf("%f,%f\n",x1,x2);
}

void B(float a,float b,float c)
{
float x;
x=-b/(2*a);
printf("%f\n",x);
}

void C(float a,float b,float c)
{
float x1,x2;
x1=(-b+sqrt(b*b-4*a*c))/(2*a);
x2=(-b-sqrt(b*b-4*a*c))/(2*a);
printf("%f,%f\n"

例x=(-b+sqrt(b^2-4ac))/2a
在这里把x分为两部分,p=-b/a和q=(sqrt(b^2-4ac))/a,然后你在输出时按这样printf("x=%f+%fi",p,q);i在这里为照样输出,希望采纳!

丫就不会开方他的绝对值,然后在得数后加个i?

都知道负数还sqrt...
void C(float a, float b, float c)
{
float xa1,xb1; // x1 = xa1 + i*xb1
float xa2,xb2; // x2 = xa2 + i*xb2
float delta;
delta = abs(b*b-4*a*c); //绝对值
xa1 = xa2 = (-b)/(2*a);
xb1 = sqrt(delta)/(2*a);
xb2 = -sqrt(delta)/(2*a);
printf("x1 = %f + %fi\n",xa1,xb1);
printf("x2 = %f + %fi\n",xa2,xb2);
}

x1=(-b+sqrt(-(b*b-4*a*c)))/(2*a);
x2=(-b-sqrt(-(b*b-4*a*c)))/(2*a);
这样不就可以了吗!~~~