gpt4 book ai didi

objective-c - [OBJ-C] [iOS]从NSArray获取 float -问题

转载 作者:行者123 更新时间:2023-12-01 18:03:18 26 4
gpt4 key购买 nike

我最近遇到了问题。这就是问题,我正在尝试从NSArray中获取一个持有该对象的float对象,而我所能获得的只是(null)。显然不是我想要接收的东西。看一下代码片段:

h = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:1.0], nil];
x = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:2.0], nil];
y = [[NSMutableArray alloc] init];

int step = 15; // That is just a random value, will depend on size of h and x.

for (int i = 0; i < step; ++i) {
NSLog(@"step = %i", i);


NSMutableArray *xTemp = [[NSMutableArray alloc] initWithArray:x];
NSMutableArray *hTemp = [[NSMutableArray alloc] initWithArray:h];

for (int j = 0; j < 3; ++j) {

float xToMul = [[xTemp objectAtIndex:j] floatValue];
float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];

NSLog(@"xToMul = %@", xToMul);
NSLog(@"hToMul = %@", hToMul);


}

NSLog(@"\n");

}

结果是:
xToMul = (null)
hToMul = (null)

我需要的是做一些简单的数学运算。

谢谢。
先生。

最佳答案

这是您的问题:

float xToMul = [[xTemp objectAtIndex:j] floatValue]; float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];
NSLog(@"xToMul = %@", xToMul); NSLog(@"hToMul = %@", hToMul);

%@用于支持-description的对象。 float根本不是对象。这段代码向float传递了-description消息,它无法响应。

有两种解决方法。

第一种是使xToMul和hToMul对象而不是float并保留格式字符串。
id xToMul = [xTemp objectAtIndex:j];
id hToMul = [hTemp objectAtIndex:(j+i)];
NSLog(@"xToMul = %@", xToMul);
NSLog(@"hToMul = %@", hToMul);

第二个是将它们保留为浮点型,但要修复格式字符串:
float xToMul = [[xTemp objectAtIndex:j] floatValue];
float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];
NSLog(@"xToMul = %f", xToMul);
NSLog(@"hToMul = %f", hToMul);

如果您打算对浮点数进行数学运算,则可能要选择此选项。

另一个有趣的地方是这个循环:
 for (int j = 0; j < 3; ++j) {

这将使用三个值(0、1和2)逐步遍历j。这对应于NSArray中的第一,第二和第三项。您在 x中有两个项目,在 h中有三个项目。我猜这只是对原始代码的简化,但在两种情况下都只是一个简短的例子。 2 + 1的j将访问 h中的第4个项目,而2的j将访问 x中的第3个项目。

关于objective-c - [OBJ-C] [iOS]从NSArray获取 float -问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4197831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com