http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
My version is spelt differently so adjust the code accordingly if copying and pasting.
Chapter 5 // Exercise 7
Quadratic equations are of the form:
There is a problem though: is b(2)-4ac is less than zero, then it will fail. Write a program that can calculate x for a quadratic equation. Create a function that prints out the roots of a quadratic equations, given a, b, c. When the program detects an equations with no real roots, have it print out a message. How do you know that your results are plausible? Can you check that they are correct?
Ok, in chapter 4, exercise 18 I already covered this and converted negative numbers into "imaginary numbers" ie. I made them positive since you can't square root a negative. I guess here, he just wants us to display a message when the number is negative instead of changing it.
#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;
double a;
double b;
double c;
double get_xPos()
{
double x = ((-b + sqrt((b*b) - (4 * a*c))) / (2 * a));
if ((b*b) - (4 * a*c) < 0)
{
cout << b << "*" << b << "-4*" << a << "*" << c << "= " << ((b*b) - (4 * a*c)) << '\n';
error("This is a negative number and cannot be rooted.\n");
}
return x;
}
double get_xNeg()
{
double x = ((-b - sqrt((b*b) - (4 * a*c))) / (2 * a));
if ((b*b) - (4 * a*c) < 0)
{
cout << b << "*" << b << "-4*" << a << "*" << c << "= " << ((b*b) - (4 * a*c)) << '\n';
error("This is a negative number and cannot be rooted.\n");
}
return x;
}
int main()
try
{
cout << "Let's solve some quadratic equations.\n";
cout << "What is a?: \n";
cin >> a;
cout << "What is b?: \n";
cin >> b;
cout << "What is c?: \n";
cin >> c;
double x1 = get_xPos();
double x2 = get_xNeg();
cout << "\nX is: " << x1 << " and " << x2 << "\n";
cout << '\n';
keep_window_open();
return 0;
}
catch (exception& e)
{
cerr << "Error: " << e.what() << '\n';
keep_window_open();
return 1;
}
You can check to see if your results are plausible by plotting x1 and x2 on a graph. They should intersect with the x axis creating a curve. If they don't intersect the x axis, you are using imaginary numbers.
No comments:
Post a Comment