1581 - 一元二次方程

建立一个求一元二次方程解的类(a*x^2+b*x+c=0),输入系数a,b,c 的值后打印出

这个方程的解

题目输入

输入第一行为样例数m,接下来m行每行3个整数a、b、c。

题目输出

输出m行,要求格式如下:若无解则输出-1,若有单解则输出x=..,若有两解则输出x1=...,x2=...,具体参见样例,保留小数点后两位。

输入/输出样例

题目输入

3
1 -3 2
1 -2 1
2 1 2

题目输出

x1=1.00,x2=2.00
x=1.00
-1

提示

注意a为0的情况。

C语言解答

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
  int n;
  long long int a,b,c,d;
  double s,x1,x2;
  scanf("%d",&n);
  while(n--){
    scanf("%lld %lld %lld",&a,&b,&c);
    if(a){
    d=b*b-4*a*c;
    if(d<0)printf("-1\n");
    else if(d==0)printf("x=%.2lf\n",(-b)/(2.0*a));
      else printf("x1=%.2lf,x2=%.2lf\n",(-b-sqrt(1.0*d))/(2.0*a),(-b+sqrt(1.0*d))/(2.0*a));}
    else{
      if(b)printf("x=%.2lf\n",(-c)/(1.0*b));
    }
  }
}

C++解答

#include<iostream>
#include<cmath>
#include <cstdio>
using namespace std;
class Root
{
    int a,b,c;
public:
    Root(int aa,int bb,int cc):a(aa),b(bb),c(cc) {}
    Root() {}
    void result();
};
void Root::result()
{
    if(a==0)
        printf("x=%.2f\n", -c*1.0/b);
    else {
        double delta=b*b-4*a*c;
        if (0 == delta)
            printf("x=%.2f\n", -b/(2.0*a));
        else if (delta < 0)
            puts("-1");
        else {
            delta = sqrt(delta);
            printf("x1=%.2f,x2=%.2f\n", (-b-delta)/(2.0*a), (-b+delta)/(2.0*a));
        }
    }
}
int main()
{
    //freopen("test.in", "r", stdin);
    //freopen("test.out", "w", stdout);
    int aa,bb,cc,t;
    cin >> t;
    while (t--) {
        cin>>aa>>bb>>cc;
        Root x(aa,bb,cc);
        x.result();
    }
    return 0;
}

提示

注意a为0的情况。

时间限制 1 秒
内存限制 32 MB
讨论 统计
上一题 下一题