#include "iostream"
#include "math.h"
usingnamespace std;
class Bhaskara {
float *x, *y, *z;
public:
Bhaskara (float, float, float);
~Bhaskara ();
float delta() { return (pow(*y, 2) - 4 * *x * *z); }
float x1() { return ((- *y + sqrt(delta())) / 2 * *x); }
float x2() { return ((- *y - sqrt(delta())) / 2 * *x); }
};
Bhaskara::Bhaskara (float a, float b, float c) {
x = newfloat;
y = newfloat;
z = newfloat;
*x = a;
*y = b;
*z = c;
}
Bhaskara::~Bhaskara () {
delete x;
delete y;
delete z;
}
int main() {
float i, j, v;
cout << "Write the value of a: ";
cin >> i;
cout << "Write the value of b: ";
cin >> j;
cout << "Write the value of c: ";
cin >> v;
Bhaskara bha(i, j, v);
if (bha.delta() < 0) {
cout << "The roots don't exist in the set of Real numbers." << endl;
} elseif (bha.delta() == 0) {
cout << "The roots are equal:\nx1 = " << bha.x1() << "\nx2 = " << bha.x2() << endl;
} else {
cout << "The roots are different:\nx1 = " << bha.x1() << "\nx2 = " << bha.x2() << endl;
}
return 0;
}
Write the value of a: 2
Write the value of b: 5
Write the value of c: -3
The roots are different:
x1 = 2
x2 = -12
Press any key to continue...
My question is: why this code returns the value without dividing the result of (- *y + sqrt(delta())) / 2 * *a) or (- *y - sqrt(delta())) / 2 * *a)?
I know it's actually more a calculation question than a code one, but I need some help.
I will show you how your code actually computes due to operator precedence (I omit the dereference operator): -y ± ( (sqrt(delta)/2) * x )
It's the same as question "what is 2+2*2"
Use parenteses to force needed order of operations.