输出格式:
在一行中输出该多项式在该区间内的根,精确到小数点后2位。
输入样例:
3 -1 -3 1
-0.5 0.5
输出样例:
0.33
idea
- 精确到小数点后两位
=>阈值为0.001
solution1
#include <stdio.h>
#include <math.h>
double f(double a[], double x);
int main(){
double arr[4], a, b;
for(int i = 0; i < 4; i++)
scanf("%lf", arr + i);
scanf("%lf%lf", &a, &b);
while(b - a > 0.001 && f(arr, b)*f(arr, a) <= 0){
if(f(arr, b) == 0){
printf("%.2f", b);
return 0;
}
else if(f(arr, a) == 0){
printf("%.2f", a);
return 0;
}
else{
double mid = (a + b) / 2;
if(f(arr, a)*f(arr, mid) < 0) b = mid;
else a = mid;
}
}
printf("%.2f", (a + b) / 2);
return 0;
}
double f(double a[], double x){
double ans = 0, power = 1;
for(int i = 3; i >= 0; i--){
ans += a[i]*power;
power *= x;
}
return ans;
}
solution2
#include <stdio.h>
#include <math.h>
double f(double a[], double x);
int main(){
double arr[4], a, b, mid;
for(int i = 0; i < 4; i++)
scanf("%lf", arr + i);
scanf("%lf%lf", &a, &b);
while(b - a > 0.001){
mid = (a + b) / 2;
if(f(arr, mid) == 0) break;
else if(f(arr, a)*f(arr, mid) < 0) b = mid;
else a = mid;
}
printf("%.2f", (a + b) / 2);
return 0;
}
double f(double a[], double x){
double ans = 0, power = 1;
for(int i = 3; i >= 0; i--){
ans += a[i]*power;
power *= x;
}
return ans;
}
solution3
#include <stdio.h>
double f(double a[], double x);
int main(){
double arr[4], a, b, mid;
for(int i = 0; i < 4; i++)
scanf("%lf", arr + i);
scanf("%lf%lf", &a, &b);
while(b - a > 0.001){
mid = (a + b) / 2;
if(f(arr, mid) == 0) break;
else if(f(arr, a)*f(arr, mid) < 0) b = mid;
else a = mid;
}
printf("%.2f", (a + b) / 2);
return 0;
}
double f(double a[], double x){
return a[0]*x*x*x + a[1]*x*x + a[2]*x + a[3];
}