⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 quadraticroots.cpp

📁 这是数据结构、算法与应用-C++语言描述的代码
💻 CPP
字号:
// find the roots of a quadratic

#include <iostream>
#include <math.h>    // has sqrt function
#include "myExceptions.h"

using namespace std;

void inputCoefficients(double& a, double& b, double& c)
{// Read in the coefficients of the quadratic.

   cout << "Enter the coefficients a, b, and c"
        << endl
        << "a should not be zero"
        << endl;
   cin >> a >> b >> c;
   if (fabs(a) <= 0.1E-9) 
       throw illegalInputData("a should be non-zero");
}

void outputRoots(const double& a, const double& b, const double& c)
{// Compute and output the roots of the quadratic.

   double d = b * b - 4 * a * c;
   if (d > 0) {// two real roots
                 double sqrtd = sqrt(d);
                 cout << "There are two real roots "
                      << (-b + sqrtd) / (2 * a) << " and "
                      << (-b - sqrtd) / (2 * a)
                      << endl;
               }
   else if (d == 0)
           // both roots are the same
           cout << "There is only one distinct root "
                << -b / (2 * a)
                << endl;
        else //  complex conjugate roots
             cout << "The roots are complex"
                  << endl
                  << "The real part is "
                  << -b / (2 * a) << endl
                  << "The imaginary part is "
                  << sqrt(-d) / (2 * a) << endl;
}
   
int main()
{
   double a, b, c;

   // test with 4 sets of coefficients
   for (int i = 1; i <= 4; i++) {
      try {
         inputCoefficients(a,b,c);
          }
      catch (illegalInputData e) {
         cout << "Caught illegalInputData exception" << endl;
         e.outputMessage();
         return 1;
          }
     
      cout << "The coefficients of the quadratic are "
           << a << " " << b << " " << c << endl;
      outputRoots(a,b,c);
      cout << endl;}
   return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -