HUST 1541 Student’s question

时间:2021-08-10 07:22:57

1541 - Student’s question

时间限制:1秒 内存限制:128兆

696 次提交 134 次通过
题目描述

YYis a student. He is tired of calculating the quadratic equation. He wants you to help him to get the result of the quadratic equation. The quadratic equation’ format is as follows: ax^2+bx+c=0.

输入

The first line contains a single positive integer N, indicating the number of datasets. The next N lines are n datasets. Every line contains three integers indicating integer numbers a,b,c (a≠0).

输出

For every dataset you should output the result in a single line. If there are two same results, you should just output once. If there are two different results, you should output them separated by a space. Be sure the later is larger than the former. Output the result to 2 decimal places. If there is no solution, output “NO”.

样例输入
3
1 2 1
1 2 3
1 -9 6
样例输出
-1.00
NO
0.73 8.27

题目链接:http://acm.hust.edu.cn/problem/show/1541

分析:此题坑点很多!比赛中看到有人WA了11次都没过!原因在于要取double型而非int型,取double,直接AC,虽然弱弱也WA了3次才想到这一点!
大意就是要求解方程的根,常规做法就是先判断△=b*b-4*a*c的值,小于0无解,输出NO;等于0,一解;大于0,两解!但要注意的是两个解要从小到大进行有序输出!
而如何求解x1,x2,根据韦达定理得:x1+x2=-b/a,x1*x2=c/a去求解x1-x2=sqrt((x1+x2)*(x1+x2)-4*x1*x2),然后就可以求出x1,x2啦!还要记得保留两位小数哟!
下面给出AC代码:
 #include <bits/stdc++.h>
using namespace std;
int main()
{
double n,a,b,c;
while(cin>>n)
{
while(n--)
{
cin>>a>>b>>c;
if(a==)break;
else
{
if(b*b-*a*c>=)
{
double t1=(-b)/a;
double t2=c/a;
double t3=sqrt(t1*t1-*t2);
double x1=(t1+t3)/;
double x2=(t1-t3)/;
if(x1==x2) cout<<fixed<<setprecision()<<x1<<endl;
else if(x1<x2)
cout<<fixed<<setprecision()<<x1<<" "<<x2<<endl;
else if(x1>x2)
cout<<fixed<<setprecision()<<x2<<" "<<x1<<endl;
}
else cout<<"NO"<<endl;
}
}
}
return ;
}