Execute a “prepared” math operation in Objective-C

北慕城南 提交于 2019-12-06 16:00:20

问题


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 is great, but to static. I also understand that this may be something hard to achieve out of the box.


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4969618/execute-a-prepared-math-operation-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!