开发者

Add up all values from NSMutableArray

开发者 https://www.devze.com 2023-04-04 23:44 出处:网络
I have a NSMutableArray, containing x different NSStrings (NSString but only numbers no letters). I would like to add up all of the values to return a single float, or int. I think I have to do this w

I have a NSMutableArray, containing x different NSStrings (NSString but only numbers no letters). I would like to add up all of the values to return a single float, or int. I think I have to do this with a for l开发者_运维问答oop, but i am very unfamiliar with for loops.... OK I have reached this point:

for (NSString *a in det) 
{
   float x = [a floatValue];
   NSLog(@"%.2f",x);
}

And this returns all the values like this in ´NSLog`:

23.00
8.00
61.00
...

How could i just add them up now?


You can avoid looping and instead use the key value coding and obtain the total

    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"1.1", @"2.2", @"3.1", nil];
    NSNumber *sum = [arr valueForKeyPath:@"@sum.floatValue"];

Variable sum will be 6.4.


Try this:

float total = 0;
for(NSString *str in det)
{
    total += [str floatValue];
}


Here is the code for a for-in if you want to save a bit of typing. It's preferable to use fast enumeration for these types of scenarios with data structures that support it.

float result = 0.0;
for(NSString *i in nsArray)
{
    result += [i floatValue];
}


int result = 0;

for(int i=0;i<[array count];i++) 
     result += [[array objectAtIndex:i] intValue];

if you need to return a float simply define result as float and use floatValue instead of intValue

0

精彩评论

暂无评论...
验证码 换一张
取 消