Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 小数相加是如何工作的?_Objective C_Ios_C_Xcode_Nsdecimalnumber - Fatal编程技术网

Objective c 小数相加是如何工作的?

Objective c 小数相加是如何工作的?,objective-c,ios,c,xcode,nsdecimalnumber,Objective C,Ios,C,Xcode,Nsdecimalnumber,我有一个情况,我需要添加两个N小数,这是我的代码: NSDecimalNumber *total = [[NSDecimalNumber alloc] initWithString:@"0"]; for (Product* product in cartItems) { NSDecimalNumber *prodPrice = [[NSDecimalNumber alloc] init]; prodPrice = product.price; total = [total

我有一个情况,我需要添加两个N小数,这是我的代码:

NSDecimalNumber *total = [[NSDecimalNumber alloc] initWithString:@"0"];
for (Product* product in cartItems) {
    NSDecimalNumber *prodPrice = [[NSDecimalNumber alloc] init];
    prodPrice = product.price;
    total = [total decimalNumberByAdding:prodPrice];
}
return total;
当我尝试添加两个数字,例如0.01和0.02时,它完全起作用,它给了我0.03

但当我使用整数时,它不起作用。例如,当我尝试将0.01和1相加时,结果是一个负数。有人能帮我解决这个问题吗


谢谢

我稍微修改了你的循环。您的代码中的分配productPrice=product.price肯定是错误的。看看这个:

NSArray *cartItems = [NSArray arrayWithObjects:@"1", @".01", nil];
NSDecimalNumber *total = [[NSDecimalNumber alloc] initWithString:@"0"];

for (NSString *price in cartItems) {
    NSDecimalNumber *prodPrice = [[NSDecimalNumber alloc] initWithString:price];
    total = [total decimalNumberByAdding:prodPrice];
}
NSLog(@"Total: %@", total);
返回

 2012-09-13 15:04:03.815 Searcher[69779:f803] TotalL 1.01

product.price
”声明为什么?它也是NSDecimalNumber。NSDecimalNumber和NSDecimal之间有很大区别……您如何检查该产品。price是您认为的产品,您如何检查最终的总数?还有,您得到的负数是多少?我正在循环中调试它,负数是-0.000000…此解决方案工作正常,但在某些特定情况下不起作用。例如,当我添加1和1.06时,结果显示1.05,这是错误的!如果我在上面循环,把两个数字设为1和1.06,结果会是1.05?我想不是。