我想找人帮忙,我必须从函数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的地方。谢谢:)。
我的代码:
#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;
}发布于 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)
https://stackoverflow.com/questions/62270159
复制相似问题