Convert NSString of a math equation to a value

前端 未结 3 544
温柔的废话
温柔的废话 2020-12-11 04:37

I would like to know how to evaluate a string representation of an equation as if it were a real equation:

if(@\"15+14==23\")
{
    //True statement...
}
els         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-11 05:29

    NSString *equation = @"15+14==29";
    
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:equation];
    
    NSExpression *LeftExp = [pred leftExpression];
    
    NSExpression *RightExp = [pred rightExpression];    
    
    
    NSNumber *left = [LeftExp expressionValueWithObject:nil context:nil];
    
    NSNumber *right = [RightExp expressionValueWithObject:nil context:nil];
    
    
    if ([left isEqualToNumber:right]) {
        NSLog(@"yes left is equal to right");
    }
    else{
        NSLog(@"yes left is NOT equal to right");
    
    }
    
    NSLog(@"left %@", left); 
    
    NSLog(@"right %@", right); 
    

提交回复
热议问题