用蛮力解方程
Using brute-force for solving equations
本文关键字:方程 更新时间:2023-10-16
我正试图用蛮力在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也是。
相关文章:
- 正弦级数方程计算不正确
- 线性丢番图方程 - 求给定区间内的解数和解
- 这个方程 x + y = x & y + x |y 成立(假设 x, y > 0)?
- 尝试创建包含简单方程的函数
- 我正在尝试根据 4 个方程找出六个值
- 在 // C++注释中使用 \\ 是否合法?(C++评论中的LaTeX方程)
- 我正在尝试在 C++ 中做一个方程,但它一直输出 1
- 查找满足浮点不等式方程的最小整数
- 用蛮力解方程
- 给定方程 : x = (((x+8)/3)%5)*5;使用赋值运算符求解上述方程(例如 +=, -=, *=)
- 为什么同一个逻辑方程在python和c++中返回两个不同的结果
- C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他
- C++ 递减和显示活动方程
- 在C++中使用RK-4求解洛伦兹方程
- 如何从用户那里获取方程的输入并在 c++ 中对其进行评估
- 如何使用OpenACC集成微分方程
- C++四元数方程程序
- 使用基本 do-while 循环求解泊松方程
- 如何将 MATLAB 长线方程转换为 C++
- 检测到堆栈粉碎C++.求解拉普拉斯方程