【问题标题】:Range comparison in ObjC / iOS [closed]ObjC / iOS中的范围比较[关闭]
【发布时间】:2013-02-25 10:56:36
【问题描述】:

在我的应用中,我有不同的分级水平

例如

70-80 Good
81-95 Excellent
60    Average

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

注意:我将70-80等数据库中的范围保存为文本。

我如何从评分级别比较这些值以获得适当的答案?

【问题讨论】:

  • 阅读?那是什么?
  • 你的意思是“评分”吗,就像学术考试的结果一样?
  • 是的。成绩作为学术测试的结果。

标签: iphone ios objective-c xcode resultset


【解决方案1】:

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

让你把字符串读成:

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

【讨论】:

    【解决方案2】:

    我会这样做:

    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");
    }
    

    【讨论】:

    • 是的,它正在工作但是对于我的文本字段,我如何限制用户仅使用这种格式输入?
    • 我的 Range 也可能是一个值。喜欢的用户可以给输入 70-80 好或 85 最好
    • 它也没有比较范围的结束值。
    【解决方案3】:

    您不应将范围作为文本存储在数据库中。这样,您每次阅读时都必须对其进行解析,并将其拆分为该年级的上限和下限。

    相反,将级别存储在表中,如下所示:

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

    这样您就可以使用WHERE 子句(如actual &gt;= minimumScore AND actual &lt;= maximumScore)轻松查询关卡名称。

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

        -(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]]);
        

        希望这能给你一些想法。

        【讨论】:

        • 哎呀,你真的应该更正你的拼写错误以及不正确的大写字母和不常见的方法命名,比如- (NSString *)getGradeWithMin:(int)minValue max:(int)maxValue
        猜你喜欢
        • 2014-03-06
        • 1970-01-01
        • 2010-09-13
        • 2017-07-02
        • 2011-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多