说明:此代码只能计算单调函数的解,批注处为函数表达式,可根据需要修改
题目要求
代码
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
double EPS = 1e-6;
double f(double x){
return x*x*x - 5*x*x + 10*x - 80;//计算x^3 - 5*x^2 + 10*x -80 = 0 的x解
}
int main(){
double root,x1 = 0, x2 = 100, y;
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;
y=f(root);
triedTimes ++;
}
printf("%.8f\n",root);
printf("%d",triedTimes);
return 0;
}
输出为
x值
计算次数