XCTAssertEqualWithAccuracy无效

Mat*_*att 5 objective-c ios

有人可以回答我为什么这个断言失败了

XCTAssertEqualWithAccuracy (1.56, 1.57, .01, @"");
Run Code Online (Sandbox Code Playgroud)

而这一个有效

XCTAssertEqualWithAccuracy (1.56, 1.57, .02, @"");
Run Code Online (Sandbox Code Playgroud)

我认为1.56距离1.57 + - .01,所以它不应该失败.

pom*_*mmy 13

你以为是错的.您认为是十进制数,但使用浮点数.在浮点运算中,1.56与1.57相差大于0.01,因为这些数字都不能准确表示.试试这个:

#define printf(...) CFShow([NSString stringWithFormat:@""__VA_ARGS__]) // makes it look like C
printf("1.56                 = %.20f", 1.56);
printf("1.57                 = %.20f", 1.57);
printf("0.01                 = %.20f", 0.01);
printf("1.57 - 1.56          = %.20f", 1.57 - 1.56);
printf("(1.57 - 1.56) - 0.01 = %.20f", (1.57 - 1.56) - 0.01);
Run Code Online (Sandbox Code Playgroud)

然后惊叹于你的控制台显示

1.56                 = 1.56000000000000005329
1.57                 = 1.57000000000000006217
0.01                 = 0.01000000000000000021
1.57 - 1.56          = 0.01000000000000000888
(1.57 - 1.56) - 0.01 = 0.00000000000000000867
Run Code Online (Sandbox Code Playgroud)

如果你想知道为什么,只需谷歌"浮点",找到许多优秀的解释,并阅读计算的基础之一.