求解一元二次方程ax^2+bx+c=0的根
#include <iostream>
#include <string>
//常用数学工具库
//官方网址 http://www.cplusplus.com/reference/cmath/
#include <cmath>
using namespace std;
//求解一元二次方程ax^2+bx+c=0的根
int main()
{
float a, b, c;//系数
float x1, x2;
cout << "请输入a的值:" << endl;
cin >> a;
cout << "请输入b的值:" << endl;
cin >> b;
cout << "请输入c的值:" << endl;
cin >> c;
cout << "您输入的方程为:" << a << "x^2+" << b << "x+" << c << "=0" << endl;
float t = b * b - 4 * a * c;//得塔
if (t < 0)
{
cout << "此方程无实数根" << endl;
}
else
{
//求根公式
x1 = (-b + sqrt(t)) / (2 * a);//sqrt(t):对t开平方
x2 = (-b - sqrt(t)) / (2 * a);
cout << "一个根x1=" << x1 << endl;
cout << "一个根x2=" << x2 << endl;
}
system("pause");
return 0;
}
转载自:黑凤梨の博客