比较两个double或两个float值的最有效方法是什么?
简单地这样做是不正确的:
bool CompareDoubles1 (double A, double B)
{
return A == B;
}
Run Code Online (Sandbox Code Playgroud)
但是像这样:
bool CompareDoubles2 (double A, double B)
{
diff = A - B;
return (diff < EPSILON) && (-diff < EPSILON);
}
Run Code Online (Sandbox Code Playgroud)
似乎浪费处理.
有谁知道更聪明的浮动比较器?
我试图比较两个相同的纬度,它是类型的Double,当我打印结果时,它被评估为false.
print("spot latitude: " + String(spot.location.latitude))
print("first object: " + String(firstSpot.location.latitude))
print(spot.location.latitude == firstSpot.location.latitude)
Run Code Online (Sandbox Code Playgroud)
输出:
spot latitude: 32.8842183049047
first object: 32.8842183049047
false
Run Code Online (Sandbox Code Playgroud)
任何人都知道发生了什么?
我知道有很多关于这个问题的主题,但这些都没有帮助我.我试图通过测试-10到10范围内的每个数字以及两个小数位来找到函数的根.我知道这可能不是最好的方式,但我是初学者,只是想尝试一下.不知怎的,循环不起作用,因为我总是得到-10作为输出.无论如何,这是我的代码:
#include <iostream>
using namespace std;
double calc (double m,double n)
{
double x;
for (x=-10;x<10 && m*x+n==0; x+=0.01)
{
cout << x << endl;
}
return x;
}
int main()
{
double m, n, x;
cout << "......\n";
cin >> m; // gradient
cout << "........\n";
cin >> n; // y-intercept
x=calc(m,n); // using function to calculate
cout << ".......... " << x<< endl; //output solution
cout << "..............\n"; // Nothing of importance
return 0;
}
Run Code Online (Sandbox Code Playgroud)