NSExpression 1/2 [英] NSExpression 1/2

查看:303
本文介绍了NSExpression 1/2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算一个字符串,我这样做:

I want to calculate a string, which I'm doing by this:

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

问题是,当计算字串是1/2时,结果是0.我试图改变float有双重和NSNumber和%f到%f和%@,但我总是只是0.我必须改变什么?

The problem is, when calculationstring is 1/2, the result is 0. I tried to change float with double and NSNumber and the %f to %f and %@, but I always just get 0. What to I have to change?

我在欧洲,所以我有逗号而不是点的这个值,但它不重要,因为我用%f记录它显示为点。仅供参考

Also if it matters, I am in Europe, so I have commas instead of points for this value, but it shouldn't matter as I am logging with %f which shows it as points. Just for information

推荐答案

输入 NSExpression 看起来像整数(不包括小数点/逗号)的文本被视为整数,因此使用整数除法。 (在整数除法下,1/2 为零。如果你想要0.5,你需要浮点除法)。当表达式被解析和求值时,会发生这种情况,所以试图改变结果的类型,

Typing in NSExpression is much like in C: literals that look like integers (no decimal point/comma) are treated as integers and thus use integer division. (Under integer division, 1/2 is zero. If you want 0.5, you need floating point division.) This happens when the expression is parsed and evaluated, so attempting to change the type of the result or the formatting of the output has no effect -- those things happen after parsing and evaluation.

如果你的 calculationString 是在解析和评估后发生的,完全在你的控制下,很容易确保你使用浮点文字在任何你想要的浮点除法。 (也就是说,使用 1.0 / 2 而不是 1/2 。)如果没有,它这样做 - 这里可能更好的是分解解析的 NSExpression 并更改操作数而不是munge字符串。

If your calculationString is entirely under your control, it's easy to make sure that you use floating point literals anywhere you want floating point division. (That is, use 1.0/2 instead of 1/2.) If not, you'll need to change it such that it does -- here it's probably better to decompose the parsed NSExpression and change an operand rather than munge the string.

这篇关于NSExpression 1/2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆