-2

I have write this code to solve a quadratic formula but it doesn't work when the answer is complex(in iota form like 3i or √-3) i want to get answer in iota how could i manage it

#include<iostream>
#include<math.h>

using namespace std;

int main(){
  float a,b,c,variable1,variable2,variable3,y,x,variable4;
  cout<<"Enter a:";
  cin>>a;
  cout<<"Enter b:";
  cin>>b;
  cout<<"Enter c:";
  cin>>c;
  variable1=-b;
  variable2=b*b;
  variable3=(4*a*c);
  variable4=(variable2-variable3);
  y=sqrtf(variable4);
  x=(variable1+y)/2;
  cout<<"x=" <<x <<endl;
}
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
Usman Qamar
  • 49
  • 1
  • 9

1 Answers1

4

The overload of std::sqrt that produces a complex result is declared in <complex> and takes a std::complex<T> as its argument, so to get a complex result, you need to start with a complex input, and include the correct header.

Here's a trivial example:

#include <complex>
#include <iostream>

int main() {
    std::complex<double> d{ -1, 0 };

    std::cout << std::sqrt(d);
}

Result:

(0,1)

Those represent the real and imaginary parts respectively, so this is 0+1i, as we'd expect.

It may also be worth noting that starting with C++ 14, the standard library defines a user-defined literal for imaginary numbers, so you could initialize d like this:

using namespace std::literals;

auto d = -1.0 + 0i;

This produces the same result, but for people accustomed to writing a complex number as a + bi, it may look a little more familiar/comfortable. The one "trick" is that it's still doing type deduction, so to get a complex<double>, you need to use -1.0 instead of -1 (which I guess would try to deduce a std::complex<int>).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111