示例
现在,考虑以下函数,该函数将数组作为参数以及另一个参数,并基于传递的参数,返回通过数组的数字的平均值,如下所示:
-(double) getAverage:(int []) arr andSize:(int) size {
int i;
double avg;
double sum;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = sum / size;
return avg;
}
现在,让我们调用上述函数,如下所示:
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
/* function declaration */
-(double) getAverage:(int []) arr andSize:(int) size;
@end
@implementation SampleClass
-(double) getAverage:(int []) arr andSize:(int) size {
int i;
double avg;
double sum =0;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = sum / size;
return avg;
}
@end
int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
SampleClass *sampleClass = [[SampleClass alloc]init];
/* pass pointer to the array as an argument */
avg = [sampleClass getAverage:balance andSize: 5] ;
/* output the returned value */
NSLog( @"Average value is: %f ", avg );
return 0;
}
当以上代码一起编译并执行时,将产生以下结果-
2020-08-14 03:10:33.438 test[24548] Average value is: 214.400000
正如您所看到的,就函数而言,数组的长度无关紧要,因为Objective-C对形式参数不执行任何边界检查。