首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何找到x1和x2的二分法?

如何找到x1和x2的二分法?
EN

Stack Overflow用户
提问于 2020-06-08 19:52:24
回答 1查看 119关注 0票数 0

我想找人帮忙,我必须从函数c *(x * x) +2*x-d中得到x1和x2,其中c等于从2.00到8.99之间的随机数,d是从用户输入的5.00到14.99之间的数字。我的问题是如何得到这两个变量?x1和x2?我写的代码只能找到x1,如何获得x2?x1和x2是函数等于0的地方。谢谢:)。

我的代码:

代码语言:javascript
运行
复制
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <random>


using namespace std;

double x1, x2, c, d, eps = 0.0001, b = 10, a=0;
int attempts=20;

double f(double x){

    return c *(x * x) + 2 * x - d;
}


int main() {

    mt19937 rnd(time(NULL));
    uniform_real_distribution <double> random(2.00, 8.99);
    c = random(rnd);
    cout << "Random c is equal to : " << c << endl;
    cout << "Enter d [real number from 5.00 -> 14.99]: ";
    cin >> d;

    while (d > 14.99 || d < 5.00) {

        cout << attempts << " Attempts left: ";
        cin >> d;
        attempts--;
        if (attempts == 0) {
            exit(1);
        }
    }

    while (abs(b - a) >= eps) {
        x1 = (a + b) / 2;
        if (f(x1) == 0.0) break;
        else if (f(x1) * f(a) <= 0) b = x1;
        else a = x1;
    }



    cout << "x1: " << x1 << endl;
    /*cout << "x2: " << x2 << endl; - how to get this number?*/
    return 0;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-08 20:11:28

对于完整的方程c * (x * x) + 2 * x - d = 0,求解x (使用解说员 )

可能的x

(-1. + std::sqrt(c * d + 1.)) / c-((std::sqrt(c * d + 1.) + 1.) / c)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62270159

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档