用 Horner 形式计算三次多项式并保留七位小数。
OJ: noi_openjudge
题目 ID: ch0103-07
难度:入门
标签:数学浮点数python
日期: 2026-07-30 23:01
题意
给出
思路
把式子改写成 x*x 并让系数顺序更清楚。
代码
Python代码
python
x, a, b, c, d = map(float, input().split())
value = ((a * x + b) * x + c) * x + d
print(f"{value:.7f}")C++代码
cpp
// talk is cheap,show me your code
#include <cstdio>
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
double x,a,b,c,d;
std::cin >> x >> a >> b >> c >> d;
double answer = a*x*x*x +b*x*x+c*x+d;
cout << fixed << setprecision(7) << answer;
return 0;
}复杂度
多项式次数固定,时间复杂度和额外空间复杂度均为
总结
多项式求值优先改写为 Horner 形式:少乘法,且更容易从代码看出系数顺序。