简体   繁体   English

从 NSArray 中找到最低的 NSInteger

[英]Finding the lowest NSInteger from NSArray

I am trying to return the lowest number in an array.我试图返回数组中的最低数字。

Parameter: arrayOfNumbers - An array of NSNumbers.参数:arrayOfNumbers - NSNumbers 数组。

Return: The lowest number in the array as an NSInteger.返回:数组中最小的数字作为 NSInteger。

The code I have thus far doesn't give me any errors, but does not pass the unit tests.到目前为止,我的代码没有给我任何错误,但没有通过单元测试。 What am I doing wrong?我究竟做错了什么?

- (NSInteger) lowestNumberInArray:(NSArray *)arrayOfNumbers {

    NSNumber* smallest = [arrayOfNumbers valueForKeyPath:@"@min.self"];
    for (NSInteger i = 0; i < arrayOfNumbers.count; i++) {
        if (arrayOfNumbers[i] < smallest) {
            smallest = arrayOfNumbers[i];
        }
    }

    NSInteger smallestValue = [smallest integerValue];
    return smallestValue;

}

This is the unit test:这是单元测试:

- (void) testThatLowestNumberIsReturned {
    NSInteger lowestNumber = [self.handler lowestNumberInArray:@[@3, @8, @-4, @0]];
    XCTAssertEqual(lowestNumber, -4, @"Lowest number should be -4.");

    lowestNumber = [self.handler lowestNumberInArray:@[@83, @124, @422, @953, @1004, @9532, @-1000]];
    XCTAssertEqual(lowestNumber, -1000, @"Lowest number should be -1000.");    
}

This method这种方法

NSNumber* smallest = [arrayOfNumbers valueForKeyPath:@"@min.self"];

will already determine the smallest number in the array, so the loop inside the method is superfluous (on top of being plain wrong, as @vikingosegundo notices).将已经确定数组中的最小数字,因此该方法内的循环是多余的(除了完全错误之外,正如@vikingosegundo 所注意到的那样)。

you are comparing objects with c types, resulting im pointer addresses being compared with an int.您正在将对象与 c 类型进行比较,导致 im 指针地址与 int 进行比较。

Beside the fact your smallest is already the smallest, as you used the KVC collection operator @min.self (see Glorfindel answer), the following code shows you correct comparison除了您最小的已经是最小的这一事实之外,因为您使用了KVC 集合运算符@min.self (请参阅 Glorfindel 答案),以下代码显示了正确的比较

if (arrayOfNumbers[i] < smallest)

should be应该

if ([arrayOfNumbers[i] compare:smallest] == NSOrderingAscending)

or或者

if ([arrayOfNumbers[i] integerValue] < [smallest integerValue])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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