解二次方程c#2008-08-27 21:01:00
【评论】
【打印】
【字体:大 中 小】
本文链接:http://blog.pfan.cn/iamben250/37910.html
Determine real and complex roots of a quadratic equation ax^2 + bx + c = 0 and check results
Submitted By: horace |
|
Rating:
|
Views: 3,179 |
Language: C++ |
Last Modified: December 15, 2006 |
Instructions: enter a, b and c roots are evaluated and printed together with a test which uses the roots to evaluate ax^2 + bx + c which should be 0 |
Snippet
-
// Determine real and complex roots of a quadratic equation and check results
-
// ax^2 + bx + c = 0
-
-
#include <iostream>
-
#include <math.h>
-
#include <complex>
-
using namespace std;
-
-
int main(void)
-
{
-
float a, b, c, x1, x2, root;
-
complex<float> z;
-
-
cout << "Roots of quadratic equation, Enter a, b and c ? ";
-
cin >> a >> b >> c;
-
-
root = b * b - 4.0f * a * c; // b*b - 4ac
-
if (root >= 0.0f) // if +
-
{
-
root = sqrt(root); // real roots
-
x1 = (-b + root) / (2.0f * a);
-
x2 = (-b - root) / (2.0f * a);
-
cout << "Real roots " << x1 << " and " << x2 << endl;
-
cout << "Test " << a * x1 * x1 + b * x1 + c // check result
-
<< " and " << a * x2 * x2 + b * x2 + c << endl;
-
}
-
else
-
{ // complex roots
-
root = sqrt(-root) / (2.0f * a);
-
x1 = -b / (2.0f * a);
-
cout << "Complex roots " << x1 << " +- i " << root << endl;
-
z = complex<float>(x1, root);
-
cout << "Test " << a * z * z + b * z + c; // check result
-
z = complex<float>(x1, -root);
-
cout << " and " << a * z * z + b * z + c << endl;
-
}
-
system("pause");
-
return 0;
-
}
-
Copy & Paste |
|
阅读(2511) | 评论(0)
版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!
评论