Pregunta

I have this code

int countCosts = [Costs count];
countCosts = countCosts - 1;
NSDecimalNumber* Total = [[NSDecimalNumber alloc] initWithString:[NSString    stringWithFormat:@"%f", 0.0]];
NSDecimalNumber *cost = 0;
    while (countCosts != -1)
    {
        cost = [Costs objectAtIndex:countCosts];
        Total = [Total decimalNumberByAdding:cost];
        countCosts = countCosts - 1;
        if (countCosts < 0)
            break;
    }

Costs (Array has 1.10, 2.25, 3.50) in it. Total should equal the total of all items in cost. But equals 0;

¿Fue útil?

Solución

Your logic for adding all of the costs in the Costs array is a bit strange. Try this:

NSDecimalNumber *total = [NSDecimalNumber zero];
for (NSString *cost in Costs) {
    NSDecimalNumber *num = [NSDecimalNumber decimalNumberWithString:cost];
    total = [total decimalNumberByAdding:num];
}

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

BTW - standard naming conventions dictates that classes begin with uppercase letters while methods and variables begin with lowercase letters.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top