游客 Signup | Login
中文 | En

1842 - 课后习题8.2

通过次数

0

提交次数

0

Time Limit : 1 秒 Memory Limit : 128 MB

求方程 的根,用三个函数分别求当b^2-4ac大于0、等于0、和小于0时的根,并输出结果。从主函数输入a、b、c的值。

Input

a b c

Output

x1=? x2=?

Examples

Input Format

4 1 1

Output Format

x1=-0.125+0.484i x2=-0.125-0.484i

Solution C

#include<stdio.h>
#include<math.h>
main()
{
	int a,b,c,t;
	double n,m;
	scanf("%d %d %d",&a,&b,&c);
	m=(-b)*1.0/(2*a);
	t=b*b-4*a*c;
	if(t>0)
	{
		n=sqrt(t)/(2*a);
		printf("x1=%.3f x2=%.3f\n",m+n,m-n);
	}
	else
	{
		if(t==0)
			printf("x1=%.3f x2=%.3f\n",m,m);
		else
		{
			t=-t;
			n=sqrt(t)/(2*a);
			printf("x1=%.3f+%.3fi x2=%.3f-%.3fi\n",m,n,m,n);
		}
	}
}

Solution C++

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
double disc,x1,x2,p,q;
void big(int a,int b)   //>0
{
    x1=(-b+sqrt(disc))/(2.0*a);
    x2=(-b-sqrt(disc))/(2.0*a);
}
void small(int a,int b) //<0
{
    p=-1.0*b/(2*a);
    q=sqrt(-disc)/(2*a);
}
void equal(int a,int b) //==0
{
    x1=x2=-1.0*b/(2*a);
}
int main()
{
    int a,b,c;
    cin>>a>>b>>c;
    disc=b*b-4*a*c;
    if (disc>0)
    {
        big(a,b);
        printf("x1=%.3lf x2=%.3lf\n",x1,x2);
    }
    else if (disc==0)
    {
        equal(a,b);
        printf("x1=x2=%.3lf\n",x1);
    }
    else
    {
        small(a,b);
        printf("x1=%.3lf+%.3lfi x2=%.3lf-%.3lfi\n",p,q,p,q);
    }
    return 0;
}