读入 x 与系数 a、b、c、d,按 f(x)=ax³+bx²+cx+d 求值并保留 7 位小数输出。
OJ: roj
题目 ID: 1012
难度:入门
标签:入门数学浮点数python
创建: 2026-09-29 13:20
更新: 2026-10-04 22:31
题目描述
给定三次多项式
输入样例:
text
2.31 1.2 2 2 3输出样例:
text
33.0838692思路
直接代入公式:fixed + setprecision(7) 同时完成四舍五入与补尾零。
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 13:20
# update_at: 2026-09-29 13:20
import sys
def poly_value(x: float, a: float, b: float, c: float, d: float) -> float:
"""求三次多项式 f(x) = a x^3 + b x^2 + c x + d 的值。"""
return a * x * x * x + b * x * x + c * x + d # 乘加顺序与 std 一致,末位也相同
def solve() -> None:
x, a, b, c, d = map(float, sys.stdin.buffer.read().split()) # 题面首个实数是 x
print(f"{poly_value(x, a, b, c, d):.7f}") # .7f 四舍五入到小数点后 7 位
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-04 22:30
* update_at: 2026-10-04 22:30
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
double x, a, b, c, d; // x 与多项式系数 a、b、c、d
// 计算三次多项式 f(x) = ax^3 + bx^2 + cx + d 的值
double poly_value() {
return a * x * x * x + b * x * x + c * x + d;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> x >> a >> b >> c >> d; // 题面首个实数是 x
cout.setf(ios::fixed);
cout << setprecision(7) << poly_value() << "\n";
return 0;
}