![](/img/trans.png)
[英]How to add and update the objects of two dimensional array in objective-c?
[英]Add diagonal of 2 dimensional array in Objective C
給定:2維數組:
[[1 2 3]
[4 5 6]
[9 8 9 ]]
需要添加數組的對角線:1 + 5 + 9 = 15
NSMutableArray *array = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:@1,@2,@3,nil],
[NSMutableArray arrayWithObjects:@4,@5,@6,nil],
[NSMutableArray arrayWithObjects:@9,@8,@9,nil],nil];
NSNumber* total = 0;
for (NSNumber* row in array) {
total = total + array[row][row];
}
NSLog(@"%@",total);
在這里,我無法訪問數組的元素。 它在“ array [row] [row]”上給出錯誤。 在Objective-C中初始化2D數組和訪問數組元素的最佳方法是什么?
在您的代碼中,您正在執行的操作: for (NSNumber* row in array)
,將array
每個元素放在row
變量內(這稱為數組枚舉 btw)。
您需要使用數組的索引 -而不是每個元素的值 (這就是您在上面所做的事情)。
同樣,您不必使用對象( NSNumber *
)進行計算。 一個簡單的NSInteger即可。
這是代碼:
NSMutableArray *array = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:@1,@2,@3,nil],
[NSMutableArray arrayWithObjects:@4,@5,@6,nil],
[NSMutableArray arrayWithObjects:@9,@8,@9,nil],nil];
NSInteger total = 0;
for (NSUInteger row = 0; row < array.count; row ++) {
total = total + [array[row][row] integerValue]; // integerValue converts the NSNumber to an NSInteger
}
NSLog(@"%d",total);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.