1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
// chap4_ex18.cpp : Defines the entry point for the console application.
// Osman Zakir
// 10 / 22 / 2016
// Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 4 Exercise 18
// Program for solving quadratic equations using the quadratic formula
// Prints out the two solutions if both are real solutions,
// but otherwise informs the user that one or both solutions are NaN (not a number)
// or INF (infinite)
#include "std_lib_facilities.h"
double get_value();
double calculate_x1(double a, double b, double c);
double calculate_x2(double a, double b, double c);
int main()
{
cout << "Enter the first coefficient (a):\n";
double a = get_value();
cout << "Enter the second coefficient (b):\n";
double b = get_value();
cout << "Enter the third coefficient (c):\n";
double c = get_value();
double x1 = calculate_x1(a, b, c);
double x2 = calculate_x2(a, b, c);
if (isnan(x1) || isnan(x2))
{
cout << "One or both solutions of the given quadratic equation is/are NaN (not a number)\n";
}
else if (isinf(x1) || isinf(x1))
{
cout << "One or both solutions of the given quadratic equation is/are INF (infinite)\n";
}
else if (!isnan(x1) || !isnan(x2))
{
cout << "The first solution is " << x1 << "\n";
cout << "The second soltuion is " << x2 << "\n";
}
else if (!isinf(x1) || !isinf(x2))
{
cout << "The first solution is " << x1 << "\n";
cout << "The second solution is " << x2 << "\n";
}
}
double get_value()
{
double number;
cin >> number;
cin.ignore(32767, '\n');
return number;
}
double calculate_x1(double a, double b, double c)
{
double discriminant = pow(b, 2) - sqrt(4.0 * a * c);
double x1 = (-b) + sqrt(discriminant);
x1 = x1 / 2 * a;
// for debugging purposes
cout << "Discriminant: " << discriminant << "\n";
return x1;
}
double calculate_x2(double a, double b, double c)
{
double discriminant = pow(b, 2) - sqrt(4.0 * a * c);
double x2 = (-b) - sqrt(discriminant);
x2 = x2 / 2 * a;
return x2;
}
|