gpt4 book ai didi

ios - 获取二进制表达式 ('id' 和 'id' 的无效操作数)和错误的计算值

转载 作者:行者123 更新时间:2023-11-28 18:33:18 25 4
gpt4 key购买 nike

当我尝试对存储在数组中的值进行一些基本数学运算时,收到此错误“二进制表达式('id' 和 'id')的操作数无效”。注释掉的代码有效,但由于某种原因给出了错误的值。

@implementation OMOGradesViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
// Call init method implemented by the superclass
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if(self){
// Create array of grades
self.grades = @[@80, @70, @60, @50, @40];
// self.grades = @[@"80", @"70", @"60", @"50", @"40"];

}

// Return the address to the new object
return self;
}

- (IBAction)calculateAvg:(id)sender
{

for(NSArray *a in self.grades)
NSLog(@"%@", a);

int *avg = ([self.grades objectAtIndex:0] + [self.grades objectAtIndex:1]);

/*int avg = ((int)self.grades[0] + (int)self.grades[1] + (int)self.grades[2]
+ (int)self.grades[3] + (int)self.grades[4])/5;

NSString *strFromInt = [NSString stringWithFormat:@"%d",avg];

self.averageLabel.text = strFromInt;
NSLog(@"%@", strFromInt);*/


}

@end

最佳答案

这里有很多地方是错误的。这:

int *avg = ([self.grades objectAtIndex:0] + [self.grades objectAtIndex:1]);

应该是:

int avg = [self.grades[0] intValue] + [self.grades[1] intValue];

您不能直接添加 NSNumber 对象。您需要获取它们的 int 值(使用 intValue)。

而且您的 avg 不能是 int 指针,只是一个普通的旧 int

我还用现代数组访问语法替换了对 objectAtIndex: 的调用。

关于ios - 获取二进制表达式 ('id' 和 'id' 的无效操作数)和错误的计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23791312/

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