乘以double类型的数组元素

时间:2017-09-01 16:24:25

标签: ios c arrays

我有这个数组。

double numbers[] = {40.0, 8.0, 45.0, 55.0, 30.0, 10.0, 20.0};

和一些乘数

CGFloat multiplier = 2.67;

我想用乘数乘以数字数组的每个元素。 所以数组就像

double numbers[] = {106.80, 21.36, 120.15, 146.85, 80.1, 26.7, 53.4};

我正在“向'不兼容类型'id _Nonnull'的参数发送'double'。

在这个数字数组中找到max no的最简单方法是什么。

3 个答案:

答案 0 :(得分:1)

C数组比ObjC NSArray快,但当前设备速度非常快,因此使用对象编写代码通常会更好,但会降低速度,但会提高可读性。

你的问题的解决方案"我想通过乘数乘以数字数组的每个元素。什么是在该数字数组中找到最大值的最简单方法。"是:

double numbers[] = {40.0, 8.0, 45.0, 55.0, 30.0, 10.0, 20.0};
CGFloat multiplier = 2.67;
double maxValue = -DBL_MAX;
for (int i = 0; i < (sizeof(numbers) / sizeof(double)); i++) {
    numbers[i] *= multiplier; // multiply value
    maxValue = MAX(numbers[i], maxValue); // find max value
}
NSLog(@"Max=%f.2", maxValue);

输出如下:

(double) maxValue = 146.84999999999999
(double [7]) numbers = ([0] = 106.8, [1] = 21.359999999999999, [2] = 120.14999999999999, [3] = 146.84999999999999, [4] = 80.099999999999994, [5] = 26.699999999999999, [6] = 53.399999999999999)

但是,如果你错误地做错了,缺乏知识或其他什么:我强烈建议使用NSArray,除非表现是这里的已知问题。

答案 1 :(得分:1)

因为你需要一个循环来乘以每个元素你可以添加一行来检查并设置最大值

public class Student
{
    public int Id {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public virtual ICollection<StudentSchedule> Schedules {get;set;}
}
class StudentSchedule
{
    public int Id {get;set;}
    public int StudentId {get;set;}
    public string ClassName {get;set;}
    public virtual Student Student {get;set;}
}

答案 2 :(得分:0)

我会在Objective-C而不是C:

中编写代码
NSMutableArray* numbers = 
    [@[@40.0, @8.0, @45.0, @55.0, @30.0, @10.0, @20.0] mutableCopy];
CGFloat multiplier = 2.67;
[numbers enumerateObjectsUsingBlock:^(NSNumber* obj, NSUInteger idx, BOOL* stop) {
    numbers[idx] = @(obj.doubleValue * multiplier);
}];


该方法的奖励结果:您可以通过说[numbers valueForKeyPath:@"@max.self"]来获得最大值。

但是,除了Objective-C之外,我还会在Swift中编写代码。你显然是初学者,Objective-C和C不是初学者。在Swift中这很容易和简单!

var arr = [40.0, 8.0, 45.0, 55.0, 30.0, 10.0, 20.0]
let multiplier = 2.67
arr = arr.map {$0 * multiplier}
let max = arr.max()