[英]float [] array problem in objective c
I am coding in xcode by objective c. 我正在通过目标c在xcode中进行编码。 I came up with a problem. 我想到了一个问题。 I want to try like 我想尝试
declare float[] weights;
results looks like this 结果看起来像这样
weight[0] = 0.5
weight[1] = 0.4
weight[2] = 0.9
Ah 啊
NSMutableArray *weight;
Am 上午
weights = [NSMutableArray array];
for(int i=0; i < 4; i++) {
float randomNumber = arc4random() % 11;
[weights addObject:[[NSNumber alloc] initWithFloat:randomNumber]];
NSLog(@" for loops color prob weghts=%f",[weights objectAtIndex:i] );
}
I don't know what is wrong with this code. 我不知道这段代码有什么问题。 Please help me to find out? 请帮我找出来?
When I print it by NSLOG " all [weight = 0.000] and also How do I access like [weight floatvalue]. 当我通过NSLOG打印它时,全部[weight = 0.000]以及如何像[weight floatvalue]一样访问。
secondly, when I create this class to another class there are weight [0],[1],[2],[3] and no values 其次,当我将此类创建为另一个类时,权重为[0],[1],[2],[3],并且没有值
在NSLog中打印时,它应该是[[weights objectAtIndex:i] floatValue]
NSNumber is a class, not a integral type. NSNumber是一个类,而不是整数类型。
Therefore, you must use %@, not %f. 因此,您必须使用%@,而不是%f。
NSLog(@" for loops color prob weghts=%@",[weights objectAtIndex:i] );
Alternatively, use floatValue, like you said. 或者,像您所说的那样使用floatValue。 You may need to cast the object into NSNumber first (for type safety) 您可能需要先将对象转换为NSNumber(以确保类型安全)
NSNumber *number = (NSNumber *)[weights objectAtIndex:i];
NSLog(@" for loops color prob weghts=%f", [number floatValue]);
Also, you are leaking objects here, because you did not release them after putting them in the array. 另外,您正在此处泄漏对象,因为在将它们放入数组后没有释放它们。 Either release after placing them in array, or use [NSNumber numberWithFloat:] 将它们放入数组后释放,或使用[NSNumber numberWithFloat:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.