I'm trying to solve aX2 + bX + c = 0 but I can't seem to make it work with using the math header (which I'm not supposed to use).
printf("%E",(-b+(b*b-4*a*c)E0.5)/2a);
I'm trying to solve aX2 + bX + c = 0 but I can't seem to make it work with using the math header (which I'm not supposed to use).
printf("%E",(-b+(b*b-4*a*c)E0.5)/2a);
Use std::sqrt
from header <cmath>
. Also, you must write (2 * a)
, not 2a
.
Another thing: don't use the textbook formula for solving quadratic equations. Use the method described there.
If you can't use the math header, then you have to implement the square root eg. as described there:
double my_abs(double x)
{
return x > 0 ? x : -x;
}
double my_sqrt(double x)
{
static const double eps = 1e-12;
double u = x, uold;
do { uold = u; u = (u * u + x) / (2 * u); }
while (my_abs(u - uold) < eps * x);
return u;
}
That is not at all how E
works.
E
is used in floating point literals, to express a number scientific notation (more or less)
// x will be the same as 0.00104
double x = 1.04e-3
If you want to take a square root, then you should be using a sqrt
function:
sqrt(-b+(b*b-4*a*c))/2 / a
Of course, since you can't use #include <cmath>
, you'd have to roll your own!
You can't use E
as pow
in C/C++ (see for example mathematical power operator not working as expected). And the E
in the printf
will print the number as Scientific notation, you know? (like 3.9265E+2).
E
only works when you're typing out a constant floating point, like 2.2E6
. To compute exponentials, you need to use std::pow()
from <cmath>
. In this case, you could use std::sqrt()
.
I suppose with E you mean the power, but there is no such power operator in C++. Use either the pow
function or the, in your case more appropriate, sqrt
function. But these are both in <cmath>
. If you cannot use <cmath>
(homework assignment?), you might have to implement your own square root function.
I think you are confusing scientific notation (3.2E6 = 3.2 x 10^6
) with exponentiation (sqrt(5) = 5^(1/2)
), where I am using ^
for "raise to the power of". Unfortunately, c++, like C, doesn't have a built-in power operator. So you would normally use either sqrt(x)
or pow(x,0.5)
from the math library.
However, if you want to solve this without the math header, you'll have to find a different way to calculate square roots. You could write a subroutine to use the Babylonian or Heron method, for example...