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 4 Exercise // 4.18
Write a program to solve quadratic equations. A quadratic equation is of the form:
Use doubles for the user inputs for a, b and c. Since there are two solutions to a quadratic equation, output both x1 and x2.
For those of you (like me) who haven't touched the quadratic formula in almost ten years, I found this site useful as a refresher.
#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;
double get_xPos();
double get_xNeg();
double a;
double b;
double c;
int main()
{
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;
}
double get_xPos()
{
double x = ((-b + sqrt((b*b) - (4 *a*c))) / (2 * a));
if ((b*b) - (4 *a*c) < 0) //cannot square root negative, this turns it to positive
{
double q = ((b*b) - (4 * a*c))*-1;
x = (-b + sqrt(q))/(2*a);
}
return x;
}
double get_xNeg()
{
double x = ((-b - sqrt((b*b) - (4 *a*c))) / (2 * a));
if ((b*b) - (4 *a*c) < 0) //cannot square root negative, this turns it to positive
{
double q = ((b*b) - (4 * a*c))*-1;
x = (-b - sqrt(q)) / (2 * a);
}
return x;
}
Ok, I found this one really easy however Bjarne doesn't mention if he wants us to include imaginary numbers. For example you can't square root a negative number, so I created an if statement which changes it to a positive and then continues. It may give a different answer but otherwise it just kept showing invalid.
I also created separate functions for this one as I'm trying to get into the habit of removing as much as possible from int main. Here, I just forward declare the functions as the beginning by ending the function with a ';'. The computer then knows to look elsewhere for the declaration.
No comments:
Post a Comment