我寫了一個程序,從一個隨機生成的數組中排序,從最大到最小的50個整數。到目前爲止它可以工作,但它偶爾會在排序數組的末尾返回隨機零。這些零不存在於未排序的數組中,並且它們並不總是顯示。這是我的計劃:爲什麼我的排序數組偶爾會在最後返回0?
#import <Foundation/Foundation.h>
@interface Number: NSObject
- (void) start;
- (int) getValue;
- (void) counted;
- (void) placeValue: (int) a;
@end
@implementation Number
{
int x;
}
- (void) start
{
x = arc4random_uniform(1000);
if (x == 1)
{
x = x+1;
}
}
- (int) getValue
{
return x;
}
- (void) counted
{
x = 0;
}
- (void) placeValue: (int) a
{
x = a;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool
{
NSMutableArray *unsortedArray = [[NSMutableArray alloc] initWithCapacity: 50];
for (int n = 0; n < 50; n++)
{
Number *num = [[Number alloc] init];
[num start];
[unsortedArray addObject: num];
}
for (int n = 0; n < 50; n++)
{
printf("%i, ", [unsortedArray[n] getValue]);
}
printf ("unsorted array.\n\n");
int x = 0;
int y = 1001;
for (int n = 0; n < 50; n++)
{
for (int m = 0; m < 50; m++)
{
if (([unsortedArray[m] getValue] > x) && ([unsortedArray[m] getValue] < y))
{
x = [unsortedArray[m] getValue];
}
}
printf("%i, ", x);
y = x;
x = 0;
}
printf("sorted array.\n");
} return 0;
}
你說是隨機生成的陣列?是否允許零? – PaulG
arc4random_uniform確實返回0值:[see](https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man3/arc4random_uniform.3.html) – BoilingLime