-1

我正在生成一个随机方程,比如 2*3+4..... 并使用 DDMathparser 对其进行评估。这里我有一个类方法,它应该返回一个随机方程(存储在一个可变数组中),只有当它计算为一个整数时。但是它一直返回 Null,我不知道为什么。请帮帮我。!

#import "Equation.h"
#import "DDMathParser.h"

@implementation Equation
-(NSMutableArray*)randEquation{
    NSMutableArray* usableEquation=[[NSMutableArray alloc]init];
    while(1){
    NSArray *nums = @[@"1", @"2", @"3", @"4", @"5",@"6",@"7",@"8",@"9"];
    unsigned index1=arc4random()%9;
    NSString* num = [NSString stringWithFormat:@"%@", [nums objectAtIndex:index1]];
    NSArray *symbols = @[@"+", @"-", @"*", @"/"];
    unsigned index=arc4random()%4;
    NSString* symb = [NSString stringWithFormat:@"%@", [symbols objectAtIndex:index]];
        NSMutableArray *arrayOfSymbolsAndNumbers = [[NSMutableArray alloc] init];
        for( int i=0;i<=10;i++){
            if (i%2==0) {
                [arrayOfSymbolsAndNumbers addObject:num];
            }
            else{
                [arrayOfSymbolsAndNumbers addObject:symb];
            }

        }
        NSMutableString *stringOfSymbolsAndNumbers=[[NSMutableString alloc]init];
        for (NSObject * obj in arrayOfSymbolsAndNumbers)
        {
            [stringOfSymbolsAndNumbers appendString:[obj description]];


        }
        usableEquation=arrayOfSymbolsAndNumbers;
        NSNumber *result=[stringOfSymbolsAndNumbers numberByEvaluatingString];
        float resultFloat = [result floatValue];
        float checker=resultFloat;
        if (floor(checker)==checker) {
            break;
        }
        else{
            continue;
        }
    }
    return usableEquation;
}

@end
4

1 回答 1

0

NSLog(@"数组的内容是%@",[equation randEquation]);

根据您的代码,此日志输出The content of array is(null)意味着equation为零。您的randEquation(虽然效率不高)看起来不错,但问题是您在运行日志语句时尚未创建equation实例。

于 2014-06-28T11:36:47.090 回答