与C(因此Objective-C)相比,Swift浮点运算似乎被打破了。
我们举一个简单的例子。 在C:
double output = 90/100.0; // Gives 0.9
float output = 90/100.0f; // Gives 0.9
在斯威夫特:
var output = Double(90)/Double(100.0) // Gives 0.90000000000000002
var output = Float(90)/Float(100.0) // Gives 0.899999976
发生了什么?这是一个错误还是我错过了什么?
编辑:
#import <iostream>
int main() {
double inter = 90/100.0;
std::cout << inter << std::endl; // Outputs 0.9
return 0;
}
答案 0 :(得分:3)
问题在于打印出的数字位数不同。
#include <iostream>
#include <iomanip>
int main() {
double d = 90.0 / 100.0;
float f = 90.0f / 100.0f;
std::cout << d << ' ' << f << '\n';
std::cout << std::setprecision(20) << d << ' ' << f << '\n';
}
0.9 0.9
0.9000000000000000222 0.89999997615814208984
(我在C ++中编写了这个例子,但是你会在使用硬件浮点运算的每种语言中获得相同的结果并允许这种格式化。)
如果您想了解为什么有限精度浮点数学不能给出精确的结果:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
和