计算变量并进行比较
Calculating variables and comparing them
对不起,如果之前有人问过这个问题,但我非常不确定如何制定我的搜索以获得任何相关结果。
基本上我有一个类"Wheel",在该类中,我声明了 == 运算符应该如何工作:
bool operator == (Wheel& anotherWheel){
//Circumference of a wheel, times its RPM should give its speed
//The speed will be in what ever unit the radius is, per minute
double ourSpeed = 2 * PI * radius * rpm;
double anotherSpeed = 2 * PI * anotherWheel.getRadius() * anotherWheel.getRpm();
cout << ourSpeed << " vs " << anotherSpeed << endl;
if (ourSpeed == anotherSpeed){
return true;
}
return false;
这有效,除非车轮的半径和 RPM 与其他车轮相同,但切换除外。因此,换句话说,它不会返回 true:
2*PI*3*10 vs 2*PI*10*3
即使我打印出来并且它们在控制台中完全相同(除非我的基本数学知识完全失常,否则它们应该是这样(。
我设法通过在计算速度时添加偏执来解决这个问题:
double ourSpeed = 2 * PI * (radius * rpm);
double anotherSpeed = 2 * PI * (anotherWheel.getRadius() * anotherWheel.getRpm());
但我想了解为什么会发生这种情况,PI 只是我声明的常量双精度,所以这无关紧要。
谢谢!
小心浮点数。
一组浮点数的添加可能会有所不同,具体取决于您添加它们的顺序。乘法和各种其他运算也是如此。
这是因为由于精度限制而发生的舍入。
例如 1/3 + 1/3 = 2/3
然而
0.333333334 + 0.33333334 = 0.6666668而不是 0.66666667,这是理想的 2/3。
您需要使用容差级别来确定该值是否"足够接近"以被视为相等。
一个非常基本(幼稚和不灵活(的选项是这样的:
if(fabs(a - b) < 0.001)
但是有更好的方法。
如果你真的想了解浮点数,从这里开始:Oracle 浮点数 - 它会告诉你你需要知道的一切,除此之外还有更多。
相关文章:
- 比较C++变量的最有效方法
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- 如何使用变量模板比较 C++ 17 中的变量类型?
- 访问类对象以与全局变量进行比较
- 需要使用 3 个变量在没有函数的情况下进行比较
- 我如何将一个变量与另一个变量进行比较,例如我想如果(var1 > var2 x 1),然后执行此 c++
- 如何使用std::lower_bound比较对象变量,而不使用第二个对象进行比较
- 如何比较两个tm(来自ctime)变量
- 将系统时间与变量进行比较 - C++
- 为什么将三个变量与 == 一起比较会计算为 false?
- 将私有对象变量与用户输入的变量进行比较
- C++ 如何禁用具有不同符号变量比较的特定行的编译器警告?
- 比较 JSON::Value 变量中的数据,然后更新到文件
- 字符串比较在与变量一起使用时给出不同的输出
- 我正在比较两个具有相同值的变量,但它说它们是不同的
- 无法使用变量来比较 c++ 中的字符串
- 如何比较字符串形式的临时变量
- 比较 C++ 中的两个浮点变量
- 计算变量并进行比较
- 如何将比较运算符应用于两个匿名结构中的每个变量