开发者

Execute a "prepared" math operation in Objective-C

开发者 https://www.devze.com 2023-02-10 10:45 出处:网络
I want to to math operations with some kind of prepared formula that would look like tan(%f)*1000 or %f+%f where the %f has to be replaced by an argument.

I want to to math operations with some kind of prepared formula that would look like tan(%f)*1000 or %f+%f where the %f has to be replaced by an argument.

Is there a function in Objective-C that I can pass the format of my formula and the required numbers to execute this prepared operation?

I hope the problem is described understandable, if not, leave a comment.

Thanks in advance.

Edit 1: Thanks for your answers so far, but I'm looking for something more dynamic. The block and inline function 开发者_JS百科is great, but to static. I also understand that this may be something hard to achieve out of the box.


You may be interested in DDMathParser, found here. I believe it will do everything you're looking for.


There is nothing that would do it this way, however what you could do is rewrite your "format" into a function, and just pass the arguments it needs to have, much faster and much easier.

inline float add(float p_x,float p_y)
{ return p_x+p_y; }

inline is a compiler feature that you can use to speed things up. It will replace the function call with the code it executes when you compile. This will result in a lager binary though.


If I understand your question correctly, Objective-C Blocks are great for this.

typedef double (^CalcBlock)(double);
CalcBlock myBlock = ^(double input) {
    return (tan(input) * 1000);
};

NSLog(@"Result: %f", myBlock(M_PI_2));

You can pass the block that contains your algorithm to other objects or methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消