我需要在我的应用程序中添加一些东西来计算一组数字的平均值。
如果我有 3 个数字:10、20 和 30,我如何取数组中的所有数字,将它们加在一起 (60),然后除以总数并将最终数字呈现在某个地方,就像一个标签?
我需要在我的应用程序中添加一些东西来计算一组数字的平均值。
如果我有 3 个数字:10、20 和 30,我如何取数组中的所有数字,将它们加在一起 (60),然后除以总数并将最终数字呈现在某个地方,就像一个标签?
In addition to katzenhut's suggestion of manually calculating the average, you can use KVC collection operators, too, e.g.:
NSArray *array = @[@10, @25, @30];
NSNumber *average = [array valueForKeyPath:@"@avg.self"];
Or, if dealing with objects, for example a "Product" model object with this interface:
@interface Product : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic) double price;
- (id)initWithName:(NSString *)name price:(double)price; // the corresponding implementation should be obvious, so I'll not include it in this code snippet
@end
You could then do:
NSMutableArray *products = [NSMutableArray array];
[products addObject:[[Product alloc] initWithName:@"item A" price:1010.0]];
[products addObject:[[Product alloc] initWithName:@"item B" price:1025.0]];
[products addObject:[[Product alloc] initWithName:@"item C" price:1030.0]];
NSNumber *average = [products valueForKeyPath:@"@avg.price"];
If you want to take the results and populate a label with the results, you might do something like:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.maximumFractionDigits = 2; // two decimal places?
self.averageLabel.text = [formatter stringFromNumber:average];
The advantage of NSNumberFormatter
over stringWithFormat
is that you have greater control over the string representation of the number, e.g. it can observe localization, employ thousandths separators, etc.
您应该有一个包含单元格值的数组,并且您应该在编辑单元格时更新该数组。因此,将这些值加起来以备后用(例如,在名为 的浮点数中total
)。
float total;
total = 0;
for(NSNumber *value in myArray){
total+=[value floatValue];
}
将总数除以计数,您就完成了。喜欢float average = total/myArray.count
你应该有一个合适的数据模型。例如,如果您有 30 个单元格,则无需在表格视图中显示所有 30 个单元格。这样做会浪费资源,这也是为什么我们总是在 tableview 委托中实现 dequereuseable 方法的原因。
话虽如此,做这样的事情
#import <UIKit/UIKit.h>
@interface ViewController : UITableViewController
@end
实现如下
#import "ViewController.h"
@interface ViewController ()
{
NSArray *numbersList;
}
-(float) calculateAvg;
@end
@implementation ViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
numbersList = [[NSArray alloc]initWithObjects:@"10",@"23",@"34",@"43",@"57",@"64",@"77",@"88",@"95",nil];
[[self tableView] setDelegate:self];
[[self tableView] setDataSource:self];
}
#pragma mark - 表格视图数据源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section. Plus one to hold average
return [numbersList count] + 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
if([indexPath row] < [numbersList count])
{
[[cell textLabel] setText:[numbersList objectAtIndex:[indexPath row]]];
}
else
{
float avg = [self calculateAvg];
[[cell textLabel] setText:[NSString stringWithFormat:@"%f",avg]];
}
return cell;
}
-(float) calculateAvg
{
float avg = 0;
for(int idx=0;idx<[numbersList count];idx++)
{
int tempValue = [[numbersList objectAtIndex:idx] intValue];
avg = avg + tempValue;
}
return (avg / [numbersList count]);
}