Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective c operations with variables

Is there a relatively easy way to use mathematical operators with string variables in Objective C?

For example:

The string "x*x" should return "x^2"

The string "x/x" should return "1"

I'm looking for something that would actually use the variable name "x" without an assigned numerical value and return an answer in terms of "x".

like image 304
Amendale Avatar asked Nov 03 '22 23:11

Amendale


2 Answers

If you put the 'x' value as string then you can evaluate it as :

NSString *string=@"3*3";
NSExpression *expression = [NSExpression expressionWithFormat:string];
float result = [[expression expressionValueWithObject:nil context:nil] floatValue];
NSLog(@"%f", result);

Also,

NSString *string=@"34*(2.56+1.79)-42/1.5";
NSNumber *result=[NSExpression expressionWithFormat:string];
NSLog(@"%@", result);

Change to any datatype float to int etc as per your requirement

like image 192
Anoop Vaidya Avatar answered Nov 15 '22 06:11

Anoop Vaidya


I've had a look for an Objective C lib doing algebraic manipulation and haven't found much yet.

So your best bet might be to use a C library (Objective C is a superset of ANSI C, after all, and you can mix the the two).

Check out this list of C maths libs:

http://www.mathtools.net/C_C__/Mathematics/

From that list, it seems that Mathomatic might be of use.

Two strategies for using a C library in your Objective C:

  1. Just call the C functions from your Objective C code

  2. Create an Objective C wrapper for the C library and use that (and maybe release it for others to use :)

like image 31
occulus Avatar answered Nov 15 '22 07:11

occulus