赞
踩
有等差数列1,2,3,4,5使用递归方法求和:
- - (int)sum:(int)value
- {
- if (value >5)
- {
- return self.count;
- }
-
- //在外面定义一个全局变量self.count,初始值为0
- self.count = [self sum:value+1] + value;
-
- return self.count;
- }
调用验证:
- self.count = 0;
- int result = [self sum:1];
- - (void)sum1:(NSMutableArray *)array Index:(int)index
- {
- if (index > (int)array.count-1)
- {
- return;
- }
-
- [self sum1:array Index:index+1];
- //在外面定义一个全局变量self.count,初始值为0
- self.count = self.count + [array[index] intValue];
-
- NSLog(@"self.count==%d",self.count);
- }
验证代码:
- self.count = 0;
- NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:@"11",@"6",@"8",@"65",@"33",@"56", nil];
-
- [self sum1:array Index:0];
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。