Question

So, im making an app that solves quadratic equations. The main interface simply asks the user to input the values of A, B, and C. The problem is, I'm not getting the right answer. Here's the code:

NSString *intStringa = [NSString stringWithFormat:@"%@", a.text];
int aa = [intStringa intValue];
NSString *intStringb = [NSString stringWithFormat:@"%@", b.text];
int bb = [intStringb intValue];
NSString *intStringc = [NSString stringWithFormat:@"%@", c.text];
int cc = [intStringc intValue];
double d = ( -(bb) + ( (bb)^2 - (4*aa*cc) ) ^0,5 ) / (2*aa);
double e = ( -(bb) - ( (bb)^2 - (4*aa*cc) ) ^0.5 ) / (2*aa);
label1.text = [NSString stringWithFormat:@"%lf", d];
label2.text = [NSString stringWithFormat:@"%lf", e];

Any ideas? Thanks!!!

Was it helpful?

Solution

Use :

There is no ^ operator for root. use sqrt or pow(base,exp).

double d = ( -bb + sqrt( bb*bb - 4*aa*cc ) ) / (2*aa);
double e = ( -bb - sqrt( bb*bb - 4*aa*cc ) ) / (2*aa);

or,

double d = ( -bb + pow(( bb*bb - 4*aa*cc ), 0.5) ) / (2*aa);
double e = ( -bb - pow(( bb*bb - 4*aa*cc ), 0.5) ) / (2*aa);

OTHER TIPS

You can't use ^ for exponentiation in C and related languages (C++, Objective-C, etc) - it's a bitwise XOR operator.

Change:

double d = ( -(bb) + ( (bb)^2 - (4*aa*cc) ) ^0,5 ) / (2*aa);
double e = ( -(bb) - ( (bb)^2 - (4*aa*cc) ) ^0.5 ) / (2*aa);

to:

#include <math.h>

...

double d = - (bb + sqrt(bb * bb - 4 * aa * cc)) / (2 * aa);
double e = - (bb - sqrt(bb * bb - 4 * aa * cc)) / (2 * aa);

There is no power ^ operator in C. You have to use pow(b,2) or simply b*b.

And why are you using stringWithFormat? Just use [a.text intValue].

int aa = [a.text intValue];
int bb = [b.text intValue];
int cc = [c.text intValue];
double d = (-bb + sqrt(bb*bb - 4*aa*cc)) / (2.0*aa);
double e = (-bb - sqrt(bb*bb - 4*aa*cc)) / (2.0*aa);
label1.text = [NSString stringWithFormat:@"%lf", d];
label2.text = [NSString stringWithFormat:@"%lf", e];

You have a couple of problems: you are using ^ as an exponentiation operator; it is not. You also have a typo in one of the "exponents": 0,5 instead of 0.5. I would write your equations as:

double d = ( -bb + sqrt( bb*bb - 4*aa*cc ) ) / (2*aa);
double e = ( -bb - sqrt( bb*bb - 4*aa*cc ) ) / (2*aa);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top