我正在尝试通过蛮力在c ++中求解一个非常简单的方程式。基本思想是增大或减小x的值,直到方程式的左侧等于右侧。我没有收到任何错误,但x的值始终为0.01或-0.01。我认为我的do / while循环有缺陷,但是您可能都比我更有经验,因此可以提供任何帮助。
#include <iostream>
using namespace std;
int main()
{
double x, y, z, q, w;
x = 0;
cout << "enter y*x + q = z*x + w in order of appearance" << endl;
cin >> y;
cin >> q;
cin >> z;
cin >> w;
if ((y-z)/(w-q) > 0) // checks if x is positive
{
do
{
(x = x + 0.01);
} while ((y * x + q) == (z * x + w));
}
else if ((y - z) / (w - q) < 0) // checks if x is negative
{
do
{
(x = x - 0.01);
} while ((y * x + q) == (z * x + w));
}
else
{
x = 0;
}
cout << "x is " << x << endl;
return 0;
}
谢谢!
几件事。
首先,在比较浮点数时,您可能希望在一个狭窄的范围内进行,通常称为epsilon。尤其如此,因为您要增加相当大的幅度-0.01。您可能跳过了想要的值。
我要做的是注意:
某些代码:
float leftSide = y * x + q;
float rightSide = z * x + w;
float delta = leftSide - rightSide;
if (abs(delta) < epsilon) {
// You're really close
}
请注意,如果y和z相同,除非q和w也相同,否则将永远无法使用。