我正在创建图表我在运行时得到5个值,所以我应该怎么知道哪个更大,以便我可以设置最大限制 我有5个varibale值;
int value3=(int)roundf(appDelegate.itemOneValue);
int value4=(int)roundf(appDelegate.itemTwoValue);
int value5=(int)roundf(appDelegate.itemThreeValue);
int value6=(int)roundf(appDelegate.itemFourValue);
int value7=(int)roundf(appDelegate.itemFiveValue);
如何检查具有较大值的上述变量。
答案 0 :(得分:2)
NSArray *allValues = @[[NSNumber numberWithInt:(int)roundf(appDelegate.itemOneValue)],
[NSNumber numberWithInt:(int)roundf(appDelegate.itemTwoValue)],
[NSNumber numberWithInt:(int)roundf(appDelegate.itemThreeValue)],
[NSNumber numberWithInt:(int)roundf(appDelegate.itemFourValue)],
[NSNumber numberWithInt:(int)roundf(appDelegate.itemFiveValue)]];
int max = [[allValues valueForKeyPath:@"@max.intValue"] intValue];
或
NSNumber * max = [allValues valueForKeyPath:@"@max.intValue"];
一种不太灵活但可能更容易理解的替代方案:
int max = (value2 < value1) value2 : value1;
max = (value3 < max) value3 : max;
max = (value4 < max) value4 : max;
max = (value5 < max) value5 : max;
max = (value6 < max) value6 : max;
max = (value7 < max) value7 : max;
// now max contains the highest of all values.
答案 1 :(得分:0)
您可以阅读维基百科上的精彩文章:http://en.wikipedia.org/wiki/Selection_algorithm
这里是从数组中获取min / max的伪代码:
function select(list[1..n], k)
for i from 1 to k
minIndex = i
minValue = list[i]
for j from i+1 to n
if list[j] < minValue
minIndex = j
minValue = list[j]
swap list[i] and list[minIndex]
return list[k]
在objc中,伪代码变成了这样的东西:
int value3=(int)roundf(appDelegate.itemOneValue);
int value4=(int)roundf(appDelegate.itemTwoValue);
int value5=(int)roundf(appDelegate.itemThreeValue);
int value6=(int)roundf(appDelegate.itemFourValue);
int value7=(int)roundf(appDelegate.itemFiveValue);
NSArray *values = @[[NSNumber numberWithInt:value3],
[NSNumber numberWithInt:value4],
[NSNumber numberWithInt:value5],
[NSNumber numberWithInt:value6],
[NSNumber numberWithInt:value7]];
NSNumber min=0;
NSNumber max=0;
for ( int i=0; i<[values count]; i++ ) {
min = [values objectAtIndex:i];
//etc...
for (int j=0; j<i+1; j++ ) {
if ( [values[j] > min] ) {
// etc..
}
}
}
希望这会有所帮助。