【题目描述】
形如:ax3+bx2+cx+d=0ax3+bx2+cx+d=0 这样的一个一元三次方程。
给出该方程中各项的系数(a,b,c,da,b,c,d均为实数),并约定该方程存在三个不同实根(根的范围在−100−100至100100之间),且根与根之差的绝对值≥11。要求由小到大依次在同一行输出这三个实根(根与根之间留有空格),并精确到小数点后22位。
【输入】
一行,包含四个实数a,b,c,da,b,c,d,相邻两个数之间用单个空格隔开。
【输出】
一行,包含三个实数,为该方程的三个实根,按从小到大顺序排列,相邻两个数之间用单个空格隔开,精确到小数点后22位。
【输入样例】
1.0 -5.0 -4.0 20.0【输出样例】
-2.00 2.00 5.00
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iomanip>
using namespace std;
double a, b, c, d;
double f(double x)
{
return a * x * x * x + b * x * x + c * x + d;
}
int main()
{
cin >> a >> b >> c >> d;
double x;
for (x = -100; x <= 100; x++)
{
double x1 = x, x2 = x + 1;
if (f(x1) == 0)
{
printf("%.2f", x1); cout << " ";
}
else if (f(x1) * f(x2) < 0)
{
while (x2 - x1 >= 0.001)x1x2距离0.001满足精度要求
{
double x3 = (x2 + x1) / 2;
if (f(x3) * f(x1) <= 0)
x2 = x3;
else x1 = x3;
}
printf("%.2f", x1); cout << " ";
}
}
}
【题目描述】
有函数:f(x)=x5−15x4+85x3−225x2+274x−121f(x)=x5−15x4+85x3−225x2+274x−121
已知f(1.5)>0,f(2.4)<0f(1.5)>0,f(2.4)<0 且方程f(x)=0f(x)=0 在区间[1.5,2.41.5,2.4] 有且只有一个根,请用二分法求出该根。
【输入】
(无)
【输出】
该方程在区间[1.5,2.41.5,2.4]中的根。要求四舍五入到小数点后66位。
【输入样例】
(无)【输出样例】
(无)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iomanip>
using namespace std;
double f(double x) {
return x * x * x * x * x - 15 * x * x * x * x + 85 * x * x * x - 225 * x * x + 274 * x - 121;
}
int main() {
double low, mid, high;
low = 1.5; high = 2.4;
while (low <= high) {
mid = (low + high) / 2;
if (f(mid)>1e-7) low = mid + 1e-7;
else high = mid - 1e-7;
}
printf("%.6lf\n", low);
}