ObjC / iOS中的范围比较

时间:2013-02-25 10:56:36

标签: iphone ios objective-c xcode resultset

在我的应用中,我有不同的评分等级

e.g。

70-80 Good
81-95 Excellent
60    Average

然后我有一个测试结果值,如77或88。

注意:我将数据库中的范围保存为70-80格式。

如何比较评分等级的这些数值以获得适当的答案?

5 个答案:

答案 0 :(得分:2)

您需要从数据库或核心数据或文本文件中读取字符串。

让你读取字符串:

NSString *gradeRange=@"70-80";
NSArray *breakRange=[gradeRange componentsSeparatedByString:@"-"];

NSInteger score=77;

if( (score > [breakRange[0] integerValue]) && (score < [breakRange[0] integerValue]) ){
     NSLog(@"%ld lies in %@.", score, gradeRange);
     //Here you can log, display as per your need
}
//else if // similarly for all ranges

答案 1 :(得分:1)

我会做这样的事情:

NSString* str_good = @"70-80"; //From the database
NSRange good_range = NSRangeFromString(str_good);
good_range.length = good_range.length-good_range.location; //Ranges are (location, length) we convert it to that format

NSString* str_excellent = @"81-95"; //From the database
NSRange excellent_range = NSRangeFromString(str_excellent);
excellent_range.length = excellent_range.length-excellent_range.location; //Ranges are (location, length) we convert it to that format

int grading = 77;


if(NSLocationInRange(grading, good_range)) {
    NSLog(@"good");
}
if(NSLocationInRange(grading, excellent_range)) {
    NSLog(@"excellent");
}

答案 2 :(得分:1)

您不应将范围存储为数据库中的文本。这样你每次阅读它时都必须解析它并将其分成该年级的上限和下限。

相反,将这些级别存储在表格中:

Name      | minimumScore | maximumScore
Excellent | 81           | 95
Good      | 70           | 80

通过这种方式,您可以使用WHERE这样的actual >= minimumScore AND actual <= maximumScore子句轻松查询关卡的名称。

答案 3 :(得分:0)

如果我理解你的问题,你可以这样做:

if (result >= 81 && result <= 95) {
    //Excellent
}

答案 4 :(得分:0)

根据您的成绩创建一个自定义方法,例如

-(NSString*)getGradeWithMin:(int)minValue max:(int)maxValue
{
    return (minValue>80 && maxValue<=100) ? @"A" : ((minValue>60 && maxValue<=80) ? @"B" : ((minValue>40 && maxValue<=60) ? @"C" : @"D"));
}

之后使用componentsSeparatedByString分隔你的最大和最小范围。

NSArray *boundary = [@"70-80" componentsSeparatedByString:@"-"];
NSLog(@"Grade is : %@",[self getGradeWithMin:[[boundary objectAtIndex:0] intValue] max:[[boundary objectAtIndex:1] intValue]]);

希望这可以给你一些想法。