Objective-C对二进制表达式无效操作数

时间:2021-12-09 19:58:56

I am getting the error:

我得到了错误:

invalid operands to binary expression ('UITextField')

二进制表达式的操作数无效('UITextField')

my .h looks like this:

我的。h是这样的:

@interface ViewController : UIViewController{

    IBOutlet UILabel *resultLabel;
    float result;
    IBOutlet UITextField *miles;
    IBOutlet UITextField *mpgLoaded;
    IBOutlet UITextField *mpgEmpty;
    IBOutlet UITextField *fuelCost;
    IBOutlet UITextField *payment;
}

-(IBAction)result:(id)sender;

-(IBAction)reset:(id)sender;


@end

And the error is coming from the calculation I am trying to do in .m:

误差来自于我在。m中的计算:

-(IBAction)result:(id)sender{
    result = payment - ((miles/mpgLoaded)*fuelCost)-((miles/mpgEmpty)*fuelCost);
    resultLabel.text = [NSString stringWithFormat:@"%.2f",result];
}

2 个解决方案

#1


5  

You need to ask each UITextField for its value (which is the text property), and convert each value from a string to a float. E.g.

您需要询问每个UITextField的值(即text属性),并将每个值从字符串转换为浮点数。如。

result = payment.text.floatValue - ((miles.text.floatValue / ...

#2


3  

You need to convert your UITextField objects into numbers that you can do arithmetic with.

您需要将UITextField对象转换为可以进行算术的数字。

The UITextField class has the property "text" which contains an NSString representing the contents of the field.

UITextField类具有属性“text”,该属性包含一个表示字段内容的NSString。

So, for example:

举个例子:

NSString *milesString = miles.text;

To convert this into a float:

将其转换为浮点数:

float milesValue = [milesString floatValue]

You can then do your arithmetic with milesValue and so on.

然后你可以用milesValue等做算术。

Of course you can simplify the assignment with:

当然,你可以用以下方法简化作业:

float milesValue = [miles.text floatValue]

#1


5  

You need to ask each UITextField for its value (which is the text property), and convert each value from a string to a float. E.g.

您需要询问每个UITextField的值(即text属性),并将每个值从字符串转换为浮点数。如。

result = payment.text.floatValue - ((miles.text.floatValue / ...

#2


3  

You need to convert your UITextField objects into numbers that you can do arithmetic with.

您需要将UITextField对象转换为可以进行算术的数字。

The UITextField class has the property "text" which contains an NSString representing the contents of the field.

UITextField类具有属性“text”,该属性包含一个表示字段内容的NSString。

So, for example:

举个例子:

NSString *milesString = miles.text;

To convert this into a float:

将其转换为浮点数:

float milesValue = [milesString floatValue]

You can then do your arithmetic with milesValue and so on.

然后你可以用milesValue等做算术。

Of course you can simplify the assignment with:

当然,你可以用以下方法简化作业:

float milesValue = [miles.text floatValue]