viewDidLoad变成一个无限循环。救命

时间:2011-06-01 15:56:30

标签: iphone objective-c xcode loops viewdidload

这可能是最容易/最蹩脚的问题。

所以我试图在viewDidLoad方法中初始化一个值为0到3的增量为0.25的数组,这里我可以看到一个无限循环。

NSArray *pickArray3 = [[NSMutableArray alloc] init];
int i = 0;
//for(i = 0.25; i<=3; i=i+0.25) 
while (i<3)
{ 
//NSString *myString = [NSString stringWithFormat:@"%d", i]; 
    i=i+0.25;
    NSLog(@"The Value of i is %d", i );
//[pickArray3 addObject:myString]; // Add the string to the tableViewArray.
 }
NSLog(@"I am out of the loop now");
self.doseAmount=pickArray3;
[pickArray3 release];

这是输出。

   2011-06-01 11:49:30.089 Tab[9837:207] The Value of i is 0
   2011-06-01 11:49:30.090 Tab[9837:207] The Value of i is 0
   2011-06-01 11:49:30.091 Tab[9837:207] The Value of i is 0
   2011-06-01 11:49:30.092 Tab[9837:207] The Value of i is 0
   // And this goes on //   
   // I am out of the loop now does not get printed //

3 个答案:

答案 0 :(得分:3)

你的i是一个整数,它永远不会增加0.25。使用浮点数或双精度数。

**float** i = 0;
//for(i = 0.25; i<=3; i=i+0.25) 
while (i<3)
{ 
//NSString *myString = [NSString stringWithFormat:@"**%f**", i]; 
    i=i+0.25;
    NSLog(@"The Value of i is **%f**", i );
//[pickArray3 addObject:myString]; // Add the string to the tableViewArray.
 }

答案 1 :(得分:0)

我是一个int。因此0+0.25 = 0

答案 2 :(得分:0)

使用float代替int

因为每次表达式值i + 0.25 =&gt; (0 + 0.25)=&gt; 0.25。

i = i+0.25;

现在你将值0.25分配给整数因此它每次变为0,while中的条件永远不会为0,因此它会转到无限循环< /强>

所以你的代码必须是

float i = 0;
//for(i = 0.25; i<=3; i=i+0.25) 
while (i<3)
{ 
//NSString *myString = [NSString stringWithFormat:@"%d", i]; 
    i=i+0.25;
    NSLog(@"The Value of i is %f", i );
//[pickArray3 addObject:myString]; // Add the string to the tableViewArray.
 }