正文

解二次方程c#2008-08-27 21:01:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/iamben250/37910.html

分享到:



Quadratic equation

Determine real and complex roots of a quadratic equation ax^2 + bx + c = 0 and check results

Submitted By: horace
Actions:
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


  1. //  Determine real and complex roots of a quadratic equation and check results
  2. //   ax^2 + bx + c = 0
  3.  
  4. #include <iostream>
  5. #include <math.h>
  6. #include <complex>
  7. using namespace std;
  8.  
  9. int main(void)
  10. {
  11.     float a, b, c, x1, x2, root;
  12.     complex<float> z;
  13.    
  14.     cout << "Roots of quadratic equation, Enter a, b and c ? ";
  15.     cin >> a >> b >> c;
  16.    
  17.     root = b * b - 4.0f * a * c;                                    // b*b - 4ac
  18.     if (root >= 0.0f)                                                    // if +
  19.         {
  20.         root = sqrt(root);                                         // real roots
  21.         x1 = (-b + root) / (2.0f * a);
  22.         x2 = (-b - root) / (2.0f * a);
  23.         cout << "Real roots " << x1 << " and " << x2 << endl;
  24.         cout << "Test " << a * x1 * x1 + b * x1 + c              // check result
  25.              << " and " << a * x2 * x2 + b * x2 + c << endl;
  26.         }
  27.     else
  28.         {                                                       // complex roots
  29.         root = sqrt(-root) / (2.0f * a);
  30.         x1 = -b / (2.0f * a);
  31.         cout << "Complex roots " << x1 << " +- i " << root << endl;
  32.         z = complex<float>(x1, root);
  33.         cout << "Test " << a * z * z + b * z + c;                // check result
  34.         z = complex<float>(x1, -root);
  35.         cout << " and " << a * z * z + b * z + c << endl;   
  36.         }
  37.     system("pause");
  38.     return 0;
  39. }
  40.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.

阅读(2403) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册