Wrong root from quadratic equation calculator - c++

I was wondering if someone could help me in this problem.
So i tested the code but it didn't show the right answer below for
equation result of x2 + 5x + 6
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
double roots() {
double a, b, c, x1, x2;
cout << "Enter quadratic equation in order (a, b, c): \n";
cin >> a >> b >> c;
double discriminant = b * b - 4 * a * c;
x1 = -b + sqrt(discriminant) / 2 * a;
x2 = -b - sqrt(discriminant) / 2 * a;
if (discriminant >= 0 && a > 1) {
cout << "Your quadratic equation is " << a << "x^2 + " << b << " x + " << c << '\n';
cout << "x1 = " << x1 << '\n';
cout << "x2 = " << x2 << '\n';
}
else if (a == 1) {
cout << "Your quadratic equation is " << "x^2 + " << b << " x + " << c << '\n';
cout << "x1 = " << x1 << '\n';
cout << "x2 = " << x2 << '\n';
}
else {
cout << "Negative value returned from (b2 - 4ac), please try again!";
exit(1);
}
}
int main() {
roots();
}

You have the formula incorrect. Try this
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant)) / (2 * a);
Notice the extra parenthesis in order to put 2*a in the denominator and have it divide both b and the sqrt().
You also need to check if discriminant >= 0 before doing so, because if it is negative there is no root and the above lines are going to fail.

Firstly, using namespace std was not used, so if you don't want to use it write std::court and std::cin. Secondly, the formula is b^2 -4ac so you need to put round brackets around b*b so that the answer is subtracted from -4ac. Then, you don't need to write else if for a==1 you can add it in the above condition as a>=1 and else put down a condition where discriminant is >=0 but a==0 which violates quadratic eq condition and you can write a cannot be equal to zero. Also, the main formula for x1 and x2 is wrong since the bracket should be applied around -b+sqroot(discriminant) so that the answer is then divided by multiplication of (2*a). Otherwise, what happens is that first sqrt is divided by 2 then multiplied by a and then added to -b.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
double roots() {
double a, b, c, x1, x2;
std::cout << "Enter quadratic equation in order (a, b, c): \n";
std::cin >> a >> b >> c;
double discriminant = (b * b)- (4 * a * c);
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant))/ (2 * a);
if (discriminant >= 0 && a >= 1) {
std::cout << "Your quadratic equation is " << a << "x^2 + " << b << " x
+ " << c << '\n';
std::cout << "x1 = " << x1 << '\n';
std::cout << "x2 = " << x2 << '\n';
}
else if (a==0){
std::cout << "a cannot be zero!";
exit(1);
}
else{
std::cout << "Negative value returned from (b2 - 4ac), please try again!";
exit(1);
}
}
int main() {
roots();
}

Related

How can I fix my C++ code to calculate Complex numbers?

I have got some problems with my main.cpp.There are some places where I do not know what I have to write to make my code work well. I will write in my code where the problems are. I write the Problem word where my code is wrong. Does anybody have an idea what I have to change to make my code work?
My code is about Complex numbers add,sub,divide,mul.
Komolex.h :
#pragma once
#include <iostream>
class NullDivision : public std::exception{};
class Complex{
private:
int n, d;
public:
Complex(int _n = 0, int _d = 1) : n(_n), d(_d)
{
if(d == 0)
{
throw NullDivision();
}
}
Complex add(const Complex &b) const
{
Complex c(n + b.n , d + b.d);
return c;
}
Complex sub(const Complex &b) const
{
Complex c(n - b.n , d - b.d);
return c;
}
Complex mul(const Complex &b) const
{
Complex c(n * b.n - d * b.d ,n * b.d - d * b.n );
return c;
}
Complex div(const Complex &b) const
{
if(b.n == 0 || b.d == 0)
{
throw NullDivision();
}
Complex c((n * d + d * b.d ) / (b.n * b.n + b.d * b.d ), (d * b.n + n * b.d )/(b.n * b.n + b.d * b.d));
return c;
}
friend Complex operator+(const Complex &a, const Complex &b)
{
return Complex(a.n + b.n , a.d + b.d);
}
friend Complex operator-(const Complex &a, const Complex &b)
{
return Complex(a.n - b.n , a.d - b.d);
}
friend Complex operator*(const Complex &a, const Complex &b)
{
return Complex(a.n * b.n - a.d * b.d ,a.n * b.d - a.d * b.n );
}
friend Complex operator/(const Complex &a, const Complex &b)
{
if(b.n == 0)
{
throw NullDivision();
}
return Complex((a.n * a.d + a.d * b.d ) / (b.n * b.n + b.d * b.d ), (a.d * b.n + a.n * b.d )/(b.n * b.n + b.d * b.d));
}
friend std::ostream& operator<< (std::ostream& o, const Complex &a)
{
o << "(" << a.n << "/" << a.d << ")";
return o;
}
};
main.cpp :
#include <iostream>
#include "Komplex.h"
using namespace std;
int main()
{ bool fut = false;
int szam;
while (fut == false){
cout << "1.Komplex számok összeadása" << endl;
cout << "2.Komplex számok kivonása" << endl;
cout << "3.Komplex számok szorzása"<< endl;
cout << "4.Komplex számok osztása"<< endl;
cout << "5.Kilépés"<< endl;
cout << "Írjon be egy sorszámot!"<< endl;
cin >> szam;
if(szam == 5)
{
fut=true;
break;
}
cout << endl;
Complex n, d;
cout << "Adja meg az első szám valós részét" << endl;
cin >> n.a; // Problem
cout << "Adja meg az első szám képzetes részét" << endl;
cin >> n.b; // Problem
cout << "Adja meg a második szám valós részét" << endl;
cin >> d.a; // Problem
cout << "Adja meg a második szám képzetes részét" << endl;
cin >> d.b; // Problem
Complex eredmeny;
switch(szam){
case 1:
eredmeny = n + d;
cout << "Az eredmény:" << eredmeny.a << + eredmeny.b << "i" << endl << endl;
break;
case 2:
eredmeny = n - d;
cout << "Az eredmény:" << eredmeny.a << + eredmeny.b << "i" << endl << endl;
break;
case 3:
eredmeny = n * d;
cout << "Az eredmény:" << eredmeny.a << + eredmeny.b << "i" << endl << endl;
break;
case 4:
try {
eredmeny = n / d;
cout << "Az eredmény:" << eredmeny.a << + eredmeny.b << "i" << endl << endl;
}
catch(NullDivision e){std::cout << "NullDivision"<< std::endl;}
std::cout << std::endl;
break;
}
}
return 0;
}
Your Complex class has two member variables, n and d. You appear to be trying to put values into the (non-existent) a and b member variables.
That's not going to end well :-)
I would suggest, for a start, using variable names that make your intent clearer. For example, member variables n and d would be far better named as something like m_real and m_imag (n and d look like they should represent numerator and denominator, but that has nothing to do with complex numbers(a)).
By using decent variable names, reading of the code should be enough to figure out what's happening and you're unlikely to get confused between member variables and objects of the class (which also shouldn't be named n and d).
(a) To be honest, it looks like you've re-tasked some code meant to do rationals to be used as complex numbers. I base this on the variable naming and the fact your Complex constructor has:
Complex(int _n = 0, int _d = 1) : n(_n), d(_d)
{
if(d == 0)
{
throw NullDivision();
}
}
I can see no reason why the imaginary part of a complex number would default to one, nor why you would throw a NullDivision exception if it was zero. That would basically remove the entire set of real numbers from your complex class.
So, it's even more important that you use better names so that you can figure out why these re-tasked things are wrong.
I'm going to give you an example of how a professional developer would code up something like this (albeit without the copious comments I normally have).
I wouldn't suggest using this if this is educational classwork since you're likely to get pinged for plagiarism but it should serve as a guide on how to do it.
#include <iostream>
class ZeroDivision : public std::exception{};
struct Complex{
public:
Complex(double real_bit = 0.0, double imag_bit = 0.0)
: m_real(real_bit)
, m_imag(imag_bit)
{}
friend Complex operator+(const Complex &me, const Complex &them) {
return Complex(
me.m_real + them.m_real,
me.m_imag + them.m_imag);
}
friend Complex operator-(const Complex &me, const Complex &them) {
return Complex(
me.m_real - them.m_real,
me.m_imag - them.m_imag);
}
friend Complex operator*(const Complex &me, const Complex &them) {
return Complex(
me.m_real * them.m_real - me.m_imag * them.m_imag,
me.m_real * them.m_imag + me.m_imag * them.m_real);
}
friend Complex operator/(const Complex &me, const Complex &them) {
if (them.m_real == 0 && them.m_imag == 0)
throw ZeroDivision();
return Complex(
(me.m_real * them.m_real + me.m_imag * them.m_imag) / (them.m_real * them.m_real + them.m_imag * them.m_imag),
(me.m_imag * them.m_real - me.m_real * them.m_imag) / (them.m_real * them.m_real + them.m_imag * them.m_imag));
}
friend std::ostream& operator<<(std::ostream& os, const Complex &var) {
const char *sep = "+";
if (var.m_imag < 0)
sep = "";
os << "(" << var.m_real << sep << var.m_imag << "i)";
return os;
}
private:
double m_real, m_imag;
};
#include <iostream>
using namespace std;
int main() {
Complex c1(19.65, 3.142);
Complex c2(19.68, 2.718);
Complex c3(2, 0);
Complex c4(0, 2);
Complex c5(0, 0);
cout << c1 << " + " << c2 << " = " << (c1 + c2) << '\n';
cout << c1 << " - " << c2 << " = " << (c1 - c2) << '\n';
cout << c1 << " * " << c2 << " = " << (c1 * c2) << '\n';
cout << c1 << " / " << c2 << " = " << (c1 / c2) << '\n';
cout << c1 << " / " << c3 << " = " << (c1 / c3) << '\n';
cout << c1 << " / " << c4 << " = " << (c1 / c4) << '\n';
try {
cout << c1 << " / " << c5 << " = " << (c1 / c5) << '\n';
cout << "Did NOT successfully catch divide-by-zero\n";
} catch (ZeroDivision &exc) {
cout << "Successfully caught divide-by-zero\n";
}
return 0;
}
As part of this, I:
Got rid of superfluous stuff. There's little point having add, sub, and so on, when you can just use the built-in operators.
Created all complex numbers using the constructors (or operators). You should not be trying to change a classes internal (private) data. If you must do that, use a setter function.
Made a (very slight) adjustment to your output stream code to improve the format. And again, this is what you should use to output an object, not attempting to directly access private data.
Fixed the divide-by-zero detection. This only happens if both the real and imaginary parts are zero whereas you raised it if either were. That would bean you could never divide something by two since the imaginary part is zero, (2+0i).
Made the parts floating point rather than integers. You can change them back if you wish but the floating point is probably better in a general purpose class.
Fixed your multiplication and division formulae.
To explain that final bullet point, what you had for multiplication a * b was, where a and b are the complex numbers, R is the real part, I the imaginary:
R = a.R * b.R - a.I * b.I # correct.
I = a.R * b.I - a.I * b.R # should be adding, not subtracting
^
For division a / b, you had:
R = (a.R * a.I + a.I * b.I) / (b.R * b.R + b.I * b.I)
(a.R * a.R + a.I * b.I) / (b.R * b.R + b.I * b.I) <- should be
^
I = (a.I * b.R + a.R * b.I) / (b.R * b.R + b.I * b.I)
(a.I * b.R - a.R * b.I) / (b.R * b.R + b.I * b.I) <- should be
^
The run of that test code generates these results (reformatted for readability):
(19.65+3.142i) + (19.68+2.718i) = (39.33+5.86i)
(19.65+3.142i) - (19.68+2.718i) = (-0.03+0.424i)
(19.65+3.142i) * (19.68+2.718i) = (378.172+115.243i)
(19.65+3.142i) / (19.68+2.718i) = (1.00142+0.021348i)
(19.65+3.142i) / (2+0i) = (9.825+1.571i)
(19.65+3.142i) / (0+2i) = (1.571-9.825i)
(19.65+3.142i) / (0+0i) = Successfully caught divide-by-zero

Creating a C++ program to solve an equation of motion using Euler's method

I am trying to compute the time history of the velocity described by the equation:
dV/dt = g − (C_d/m) * V^2. g = 9.81, m = 1.0, and C_d = 1.5.
To do this I need to create a program in c++ that uses the Euler explicit method to numerically solve the equation. I am trying to find the velocity from t = 0 to t = 1 seconds with three different step sizes of delta_t = 0.05, 0.1, and 0.2 seconds. And then you are supposed to show your percent error to the analytical solution given as: V(t) = sqrt((m*g)/C_d) * tanh(sqrt((g*C_d)/m) * t).
My problem is I am not sure how to iterate through Euler's method multiple times with different time intervals. So far I have solved the analytical equation, but am unsure where to go from here. If anyone could help point me in the right direction it would be greatly appreciated.
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
double m = 1.0; // units in [kg]
double g = 9.81; // units in [m/s^2]
double C_d = 1.5; // units in [kg/m]
double t; // units in [s]
double v; // units in [m/s]
cout << "The velocity will be examined from the time t = 0 to t = 1 seconds." << endl;
cout << "Please select either 0.05, 0.1, or 0.2 to be the time interval:" << endl;
cin >> t;
cout << "You have chosen the time interval of: " << t << " seconds." << endl;
v = sqrt((m * g) / C_d) * tanh(sqrt((g * C_d) / m) * t);
cout << "The velecity at a time of "<< t << " seconds is equal to: " << v << " m/s." << endl;
return 0;
} ```
If you want to iterate over t with increments of A, calculating the result of the formula with each t, you would write a for loop.
#include <iostream>
int main()
{
double m = 1.0; // units in [kg]
double g = 9.81; // units in [m/s^2]
double C_d = 1.5; // units in [kg/m]
std::cout << "The velocity will be examined from the time t = 0 to t = 1 seconds." << std::endl;
std::cout << "Please select the time interval:" << std::endl;
std::cout << "1: 0.05" << std::endl;
std::cout << "2: 0.1" << std::endl;
std::cout << "3: 0.2" << std::endl;
double A = 0; // increment in for loop
int x;
std::cin >> x;
switch (x) { // check what the input is equal to
case 1: A = 0.05; break;
case 2: A = 0.1; break;
case 3: A = 0.2; break;
default: std::cout << "Unknown option!" << std::endl; return 1;
}
std::cout << "You have chosen the time interval of: " << A << " seconds." << std::endl;
std::cout << "Results of V(t):" << std::endl;
// this initializes a variable t as 0,
//and while t is lower than or equal to 1,
//it will increment it by a and execute the logic within the scope of the loop.
for (double t = 0; t < (1 + A); t += A) {
std::cout << "at t = " << t << ": " << sqrt((m*g) / C_d) * tanh(sqrt((g*C_d) / m) * t) << std::endl;
}
return 0;
}
Refer to https://beginnersbook.com/2017/08/cpp-for-loop/ for more information. Note: I've also introduced a switch statement into the code to prevent unknown values from being input. https://beginnersbook.com/2017/08/cpp-switch-case/

C++: handling errors, can't understand my mistake [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
1.Check the user input. If the input does not match three floating-point numbers, output an error message and do not start the calculation.
2.Check whether a==0. If so, throw a runtime_error and catch it in main, printing a message saying that a must not be 0.
The error messages should look like this:
An error occured: Malformed user input
An error occurred: a must not be zero
#include <iostream>
#include <cmath>
#include <vector>
#include <stdexcept>
using namespace std;
vector<double> solutionFinal (double a, double b, double c){
double s1, s2, discriminant;
discriminant = b*b - 4*a*c;
if (discriminant > 0){
s1 = (-b + sqrt(discriminant)) / (2*a);
s2 = (-b - sqrt(discriminant)) / (2*a);
cout << "There are 2 solutions." << endl;
cout << "The solutions are: " << s1 << " and " << s2;
return {s1, s2};
}
else if (discriminant == 0) {
cout << "There is 1 solution." << endl;
s1 = (-b + sqrt(discriminant)) / (2*a);
cout << "The solution is: " << s1;
return {s1};
}
else {
cout << "There is no solution." << endl;
return {};
}
}
int main (){
double a, b, c;
cout << "Please enter the values of a, b, and c respectively:" << endl;
try{
if (!(cin >> a >> b >> c)) {
throw runtime_error("An error occured: Malformed user input");
}
if (a == 0) {
throw runtime_error("An erorr occured: a must not be zero");
}
}
auto result = solutionFinal(a, b, c);
for (auto scalar : result){
}
catch (runtime_error& excpt) {
cout << excpt.what();
}
return 0;
}
Your code is malformed, your braces don't add up. I prefer another brace style because I think it's easier to see that way:
#include <iostream>
#include <cmath>
#include <vector>
#include <stdexcept>
using namespace std;
vector<double> solutionFinal (double a, double b, double c)
{
double s1, s2, discriminant;
discriminant = b*b - 4*a*c;
if (discriminant > 0)
{
s1 = (-b + sqrt(discriminant)) / (2*a);
s2 = (-b - sqrt(discriminant)) / (2*a);
cout << "There are 2 solutions." << endl;
cout << "The solutions are: " << s1 << " and " << s2;
return {s1, s2};
}
else if (discriminant == 0)
{
cout << "There is 1 solution." << endl;
s1 = (-b + sqrt(discriminant)) / (2*a);
cout << "The solution is: " << s1;
return {s1};
}
else
{
cout << "There is no solution." << endl;
return {};
}
}
int main ()
{
double a, b, c;
cout << "Please enter the values of a, b, and c respectively:" << endl;
try
{
if (!(cin >> a >> b >> c))
{
throw runtime_error("An error occured: Malformed user input");
}
if (a == 0)
{
throw runtime_error("An erorr occured: a must not be zero");
}
// this block was outside the try, between the try and the catch.
// it MUST be inside the try block like this
auto result = solutionFinal(a, b, c);
for (auto scalar : result)
{
}
}
catch (runtime_error& excpt)
{
cout << excpt.what();
}
return 0;
}

Don't print variable if it's zero

double a, b, c, d, x, y;
char operation
cout << setw(6) << a << b
<< setw(3) << operation
<< setw(6) << c << d
<< " = "
<< setw(6) << x << y
<< endl;
I'm making a calculator which takes two complex numbers and adds subtracts etc. My question is how do I format my output so that 0's are not displayed.
I.E. if the input is (a+bi)(c+di) the output is a+bi * c+di = x+yi But a, b, c, d, x, y are only displayed if they are nonzero.
I know I can do it with if statements and stuff but I was hoping there's a shorter, more efficient, path.
I don't think you can avoid doing the condition and printing if non-zero somewhere.
About all you can do is wrap it up so most code doesn't need to deal with it:
class complex {
double x;
double i;
public:
// ...
friend std::ostream &operator<<(std::ostream &os, complex const &c) {
// if both parts are 0, we probably want to print *something*
if (c.x == 0.0 && c.i == 0.0)
return os << 0;
if (c.x != 0.0)
os << c.x;
if (c.i != 0.0)
os << c.i << "i";
return os;
}
};
complex a, b, c;
// ...
cout << a << operation << b << " = " c << "\n";
You'll have to add a little more if you want this to honor (for example) width/precision correctly (though for real use, you undoubtedly want to use the complex class that's already in the standard library instead).
Yes, you can do it by including <complex>
std::complex<double> com_one; // value 0 + 0i
std::complex<double> com_two(3.14); // value 3.14 + 0i
std::complex<double> com_three(1.5, 3.14) // value 1.5 + 3.14i
std::complex<double> com_four(com_two); // value is also 3.14 + 0i
Then to use arithmetic operations, you can just use
std::cout << com_one + com_two << std::endl;
std::cout << com_one - 3.14 << std::endl;
std::cout << 2.75 * com_two << std::endl;
com_one += com_three / 2.0;
Source: http://stdcxx.apache.org/doc/stdlibug/20-2.html
For checking if it's a zero check it using if, and compare it with a zero. This is the most clean technique.

cardano's method in c++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
i am trying to make a program that will compute for the root of a cubic function using cardano's method
here's my code:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a, b, c, d, value;
double f, g, h;
double i, j, k, l, m, n, p, po;
double r, s, t, u;
double x1, x2, x2re, x2im, x3re, x3im, x3;
cin >> value;
for(int w=1; w <= value; w++){
cin >> a >> b >> c >> d;
cout << "CUBIC EQUATION : " << a << " x^3 + " << b << " x^2 + " << c <<" x + " << d << " = 0" << endl;
f = ((3*c/a)-((b*b)/(a*a)))/3;
g = ((2*(b*b*b)/(a*a*a))-(9*b*c/(a*a))+(27*d/a))/27;
h = ((g*g)/4)+((f*f*f)/27);
if(f==0 && g==0 && h==0){ // all roots are real and equal
x1 = pow((d/a),0.33333333333333333333333333333333);
x2 = pow((d/a),0.33333333333333333333333333333333);
x3 = pow((d/a),0.33333333333333333333333333333333);
cout << "x = " << x1 << endl;
cout << "x = " << x2 << endl;
cout << "x = " << x3 << endl;
}
else if(h<=0){ // all 3 roots are real
i = pow((((g*g)/4)-h),0.5);
j = pow(i,0.33333333333333333333333333333333);
k = acos((g/(2*i))*-1);
l = j * -1;
m = cos(k/3);
n = sqrt(3) * sin(k/3);
p = (b/(3*a))*-1;
x1 = (2*j)*m-(b/(3*a));
cout << "x = " << x1 << endl;
x2 = l * (m+n) + p;
cout << "x = " << x2 << endl;
x3 = l * (m-n) + p;
cout << "x = " << x3 << endl;
}
else if(h>0){
r = ((g/2)*-1)+pow(h,0.5);
s = pow(r,0.33333333333333333333333333333333);
t = ((g/2)*-1)-pow(h,0.5);
u = pow((t),0.33333333333333333333333333333333);
x1 = (s+u) - (b/(3*a));
cout << "x = " << x1 << endl;
x2re = (((s+u)*-1)/2) - (b/(3*a));
x2im = -(s-u)*pow(3,0.5)/2;
cout << "x = (" << x2re << "," << x2im << ")" << endl;
x3re = (((s+u)*-1)/2) - (b/(3*a));
x3im = (s-u)*pow(3,0.5)/2;
cout << "x = (" << x3re << "," << x3im << ")" << endl;
}
}
return 0;
}
can anyone help implement a user-defined ComplexNumber in this code?
I want to use this link http://en.wikipedia.org/wiki/Cubic_function but i cant understand this.
can anyone help implement a user-defined ComplexNumber in this code?
Don't implement a user-defined ComplexNumber type. Use the one provided by the language. Just #include <complex>. With that you can have a complex variable simply by complex<double> variable_name.
Code comments:
It's better to use std::sqrt(x) rather than std::pow(x, 0.5).
If you are on a POSIX-compliant machine, your math library has a cube root function, cbrt(double) in the header . (It may not be exported to the C++ header .) This too is preferable over std::pow(x,0.33333333333333333333333333333333).