Created
June 21, 2014 04:58
-
-
Save yao2030/41bbe278b54a9447ed69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
#include <math.h> | |
using namespace std; | |
const double EPS = 1e-6; | |
inline double f(double x) { return x * x * x - 5 * x * x + 10 * x - 80; } | |
int main(void) { | |
double root, x1 = 0, x2 = 100, y = 0.0; | |
root = x1 + (x2 - x1) / 2; | |
int triedTimes = 1; | |
y = f(root); | |
while (fabs(y) > EPS) { | |
if (y > 0) | |
x2 = root; | |
else | |
x1 = root; | |
root = x1 + (x2 - x1) / 2; | |
triedTimes++; | |
y = f(root); | |
} | |
cout << setprecision(10) << root << endl; | |
cout << triedTimes << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
get root of an equation using binary search.