School-Coding-Cpp/sfusi/metodoBisezione.cpp

37 lines
495 B
C++

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double f(double x) {
return pow(x, 2) - 4;
}
int main(void) {
double a = 0;
double b = 10;
int i = 0;
double m;
do {
m = (a + b) / 2;
double fm = f(m);
i++;
if (fm == 0) {
break;
} else {
if (fm > 0) {
b = m;
} else {
a = m;
}
}
} while (abs(b - a) > 1E-9 && i < 1000);
cout << m << setw(20) << abs(b - a) << endl;
return 0;
}