void RoundOffTest(double number) { // What value would you pass to RoundOffTest() in order to get this output: // BEFORE number=1.785000 round=178.000000 (round down) // AFTER NUMBER=1.785000 round=179.000000 (round up) // // It seems to round it DOWN. // But the 2nd line seems to round it UP. // Isn't that impossible? Wouldn't there be NO possible number you could pass // this function, and see that output? Or is there? NSLog(@"BEFORE number=%f round=%f (round down)", number, round(number * 100)); double NUMBER = 1.785000; NSLog(@"AFTER NUMBER=%f round=%f (round up) ", NUMBER, round(NUMBER * 100)); }
答案 0 :(得分:0)
将number
设置为1.7849995
,您将获得所看到的结果。请注意,%f
正在打印6个小数位,并且输出会四舍五入到该位数 - 因此1.7849994
将无效。
要回答您的评论问题:请使用NSNumberFormatter
。我认为所有printf
样式格式化器都是圆形的。 NSNumberFormatter
提供了7种不同的舍入模式。以下是测试功能的修改版本:
void RoundOffTest(double number)
{
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setFormat:@"0.000000"]; // see docs for format strings
[formatter setRoundingMode:NSNumberFormatterRoundFloor]; // i.e. truncate
NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithDouble:number]];
NSLog(@"%@\n", formatted);
[formatter release];
}