#include <math.h>
int main(void)
{
double a,b,c,disc,x1,x2,imagpart,realpart,m,n
printf("please input a,b,c(a!=0):\n")
scanf("%lf%lf%lf",&a,&b,&c)
disc = b * b - 4 * a * c
m = - b / (2 * a)
n = sqrt(disc) / (2 * a)
if (fabs(disc) <1e-8)
{
printf("x1=x2=%8.2f\n",x1)
}
else
if (disc >0)
{
x1 = m + n,x2 = m - n//有两个不等实根
printf("x1=%8.2f\t,x2=%8.2f\n",x1,x2)
}
else
{
realpart = m
imagpart = sqrt(-disc) / (2 * a) //有两个共轭复根
printf("x1=%8.2f+%.2fi\t,x2=%8.2f-%.2fi\n",realpart,imagpart,realpart,imagpart)
}
return 0
}
对于ax^2+bx+c=0int panduan(int a,int b,int c)
{
int m
m=b*b-4*a*c
return(m)
}
void main()
{int a,b,c,flag,x1,x2,ture,virture
printf("请依次输入二次方程的系数:\n”)
scanf("%d %d %d",&a,&b,&c)
flag=panduan(a,b,c)
if(flag>0)
{x1=(-b+sqr(flag))/(2*a)
x2=(-b-sqr(flag))/(2*a)
printf("两个不相等的实根为:x1=%d,x2=%d",x1,x2)
}
else if(flag==0)
{x1=-b/(2*a)
printf("两个相等的实根为:x1=x2=%d",x1)
}
else
{ture=-b/(2*a)
virture=sqr(-flag)/(2*a)
printf("两个不相等的虚根为:x1=%d+%di,x2=%d-%di",ture,virture,ture,virture)
}
}
程序的健壮性不是很好,适用于int型的,你可以将所有的变量都改为float,这样就可以处理其他的问题。要求输入绝对正确,3个系数之间以空格隔开!
# include <stdio.h># include <math.h>
int main(void)
{
double a, b, c
double delta
double x1, x2
char ch
do
{
printf("请输入一元二次方程的三个系数:\n")
printf("a = ")
scanf("%lf", &a)
printf("b = ")
scanf("%lf", &b)
printf("c = ")
scanf("%lf", &c)
delta = b*b - 4*a*c
if (delta >0)
{
x1 = (-b + sqrt(delta)) / (2*a)
x2 = (-b - sqrt(delta)) / (2*a)
printf("有两个解,x1 = %lf, x2 = %lf\n", x1, x2)
}
else if (0 == delta)
{
x1 = x2 = (-b) / (2*a)
printf("有唯一解,x1 = x2 = %lf\n", x1, x2)
}
else
{
printf("无实数解!\n")
}
printf("您想继续么(Y/N): ")
scanf(" %c", &ch) //%c前面必须得加一个空格 原因略
} while ('y'==ch || 'Y'==ch)
return 0
}
希望可以帮到你,如果满意请采纳!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)