2016-09-21 22 views
-3
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"22,343", @"44,323",@"34,5678",@"22,725", nil]; 

我有這個數組,我要總結兩個值這個數組。 這樣array[0] + array [1]如何求和數組的兩個元素?

如何總結這個元素? 謝謝!!

+0

你有你自己嘗試新鮮事物? – Tavo

+0

是的,我試圖增加一倍mydouble1 =陣列[0]; double mudouble2 = array [1];但是這種方法不正確 –

+2

'array [anIndex]'是你的示例代碼中的'NSString'對象,而不是'int','NSInteger'或其他原語。所以'NSInteger sum = [array [0] integerValue] + [array [1] integerValue];' – Larme

回答

0

解決方案是

NSString *strVaue1 = [array[0] stringByReplacingOccurrencesOfString:@"," withString:@""]; 
NSString *strVaue2 = [array[1] stringByReplacingOccurrencesOfString:@"," withString:@""]; 
NSUInteger arrValue1 = [strVaue1 integerValue]; 
NSUInteger arrValue2 = [strVaue2 integerValue]; 
NSUInteger sum = arrValue1 + arrValue2; 
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init]; 
[fmt setNumberStyle:NSNumberFormatterDecimalStyle]; // to get commas (or locale equivalent) 
[fmt setMaximumFractionDigits:0]; // to avoid any decimal 
NSString *result = [fmt stringFromNumber:@(sum)]; 
NSLog(@"The result is - %@",result); 

打印的結果是

The result is - 66,666 
相關問題