数组总和后缺少十进制

时间:2014-03-14 03:11:56

标签: objective-c arrays sum decimal

我想添加1.50 + 2.50 + 3.00来制作7并显示小数值7.00

NSArray *milkprice;
int sum = 0;
milkprice = [NSArray arrayWithObjects:@"1.50",@"2.50",@"3.00", nil];
for (NSDecimalNumber *milk in milkprice)    {


    NSLog (@"list = %@", milkprice);

    sum += [milk integerValue];

    NSLog (@"sum = %ld", (long) sum);

}
    NSLog (@"total = %ld", (long)sum);

NSLog返回6。

1 个答案:

答案 0 :(得分:1)

有很多错误。试试这个:

NSArray *milkprice = @[ @"1.50", @"2.50", @"3.00" ];
float sum = 0;
NSLog (@"list = %@", milkprice);
for (NSString *milk in milkprice) {
    sum += [milk floatValue];
    NSLog (@"sum = %f", sum);
}

NSLog (@"total = %f", sum);

顺便说一句 - 你为什么要使用数字字符串?