2015-06-22 51 views
2

讓我們說數字= 0和otherNumber = 10.循環將執行。但是,如果number = 10和otherNumber = 0呢?我希望編譯器選擇最小的數字並使用它繼續。如何比較兩個數字並選擇最小值以繼續執行?

我到目前爲止的代碼是在這裏:

- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber { 
    if (number <= otherNumber) { 
     NSMutableString *indices = [NSMutableString stringWithCapacity:1]; 
     for (NSInteger i= number; i <= otherNumber; i++) { 
      [indices appendFormat:@"%d", i]; 
     } 
    } else { 
     NSMutableString *indices = [NSMutableString stringWithCapacity:1]; 
     for (NSInteger i= otherNumber; i <= number; i++) { 
      [indices appendFormat:@"%d", i]; 
     } 
    } 
    return @"%@", indices; 
} 
+0

要清楚,你想一個循環,從最小變爲最大的兩個數的'號碼和'otherNumber'? – rmaddy

回答

2

一個簡單的解決方法是把的indices聲明外的條件:

- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber { 
    NSMutableString *indices = [NSMutableString stringWithCapacity:1]; 
    if (number <= otherNumber) { 
     for (NSInteger i= number; i <= otherNumber; i++) { 
      [indices appendFormat:@"%d", i]; 
     } 
    } else { 
     for (NSInteger i= otherNumber; i <= number; i++) { 
      [indices appendFormat:@"%d", i]; 
     } 
    } 
    return indices; 
} 

你可以進一步統一你是這樣的:

- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber { 
    NSInteger from, to; 
    if (number <= otherNumber) { 
     from = number; 
     to = otherNumber; 
    } else { 
     from = otherNumber; 
     to = number; 
    } 
    NSMutableString *indices = [NSMutableString stringWithCapacity:1]; 
    for (NSInteger i= from; i <= tp; i++) { 
     [indices appendFormat:@"%d", i]; 
    } 
    return indices; 
} 
+0

謝謝!那很簡單。我追着我的尾巴一個小時。大聲笑 – Kero

2

一個選項是:

- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber { 
    NSInteger minNum = MIN(number, otherNumber); 
    NSInteger maxNum = MAX(number, otherNumber); 

    NSMutableString *indices = [NSMutableString stringWithCapacity:maxNum - minNum + 1]; 
    for (NSInteger i = minNum; i <= maxNum; i++) { 
     [indices appendFormat:@"%d", i]; 
    } 

    return indices; // or [indices copy]; 
} 
1

選擇其中一個變量,始終將其視爲較大的變量,然後在函數體正確之前執行簡單的交換測試。

- (NSString *) stringWithNumbersBetweenNumber:(NSInteger)number andOtherNumber: (NSInteger)otherNumber { 
    if (number < otherNumber) { 
     NSInteger temp = number; 
     number = otherNumber; 
     otherNumber = temp; 
    } 

    NSMutableString *indices = [NSMutableString stringWithCapacity:1]; 
    for (NSInteger i= otherNumber; i <= number; i++) { 
     [indices appendFormat:@"%d", i]; 
    } 

    return @"%@", indices; 
} 

(道歉任何代碼錯誤,Objective-C的不是我的主要語言)

相關問題