quadratic equation

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 5 Exercise 7
Using std_lib_facilities.h by Bjarne Stroustrup.

//	Philipp Siedler
//	Bjarne Stroustrup's PP
//	Chapter 5 Exercise 7

//input: 1 2 3

#include "std_lib_facilities.h"

int main()
try
{
	float a, b, c, x1, x2, determinant, realNum, imagineNum;

	cout << "Enter a value for 'a', 'b' and 'c' to solve a quadratic equation.\n";

	if (cin >> a >> b >> c) {}
	else {
		error("Bad input for a, b or c");
	}

	determinant = pow(b, 2) - 4 * a * c;
	cout << "for a = " << a << ", b = " << b << ", c = " << c << "\ndeterminant = " << determinant << "\n";

	if (determinant > 0) {
		x1 = (-b + sqrt(determinant)) / (2 * a);
		x2 = (-b - sqrt(determinant)) / (2 * a);

		cout << "Roots are real and different.\n";
		cout << "x1 = " << x1 << "\n";
		cout << "x2 = " << x2 << "\n";
	}

	else if (determinant == 0) {
		x1 = (-b + sqrt(determinant)) / (2 * a);

		cout << "Roots are real and same.\n";
		cout << "x1 = x2 " << x1 << "\n";
	}

	else {
		realNum = -b / (2 * a);
		imagineNum = sqrt(-determinant) / (2 * a);

		cout << "Roots are complex and different.\n";
		cout << "imagined part + real part: x1 = " << realNum + imagineNum << "\n";
		cout << "imagined part - real part: x2 = " << realNum - imagineNum << "\n";
	}

	keep_window_open(".");
}
catch (runtime_error e) {
	cout << e.what() << "\n";
	keep_window_open(".");
}
catch (...) {
	cout << "Extiting" << "\n";
	keep_window_open(".");
}
Output:
Enter a value for 'a', 'b' and 'c' to solve a quadratic equation.
1
2
3
for a = 1, b = 2, c = 3
determinant = -8
Roots are complex and different.
imagined part + real part: x1 = 0.414214
imagined part - real part: x2 = -2.41421
Please enter . to exit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.