简体   繁体   中英

How to do primary maths with cocoa and cocoa touch

I'm quite new to xcode and am making a app where you put two numbers in to a text input and I don't know how to make xcode to do the adding sum, I tried this but it did not work

       self.answer.text = self.label.text + self.label2.text

Does anybody know how to do this.

Use :

NSInteger firstNumber=[self.label.text integerValue];
NSInteger secondNumber=[self.label2.text integerValue];
NSInteger total=firstNumber + secondNumber;
NSString *string=[NSString stringWithFormat:@"%d",total];

self.answer.text = string;

If you want to take double value replace integerValue with doubleValue

Here is another interesting way:

//Some string with expression which was taken from self.label.text
NSString *s = @"2*(2.15-1)-4.1";
NSExpression *expression = [NSExpression expressionWithFormat:s];
float result = [[expression expressionValueWithObject:nil context:nil] floatValue];
NSLog(@"%f", result);
self.answer.text=[NSString stringWithFormat:@"%f",result];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM