1. 2021年信奥赛C++提高组初赛阅读程序题解析
作为参加过多次信息学奥赛的选手,我深知阅读程序题在初赛中的重要性。这类题目不仅考察代码理解能力,更是检验选手对算法细节把握程度的试金石。今天我们就来详细拆解2021年CSP-S提高组初赛的第一道阅读程序题,我会从代码解析、执行过程模拟到选项分析,带大家完整走一遍解题思路。
1.1 题目代码初步观察
首先我们来看题目给出的完整代码:
cpp复制#include <iostream>
#include <cmath>
using namespace std;
const double pi = 3.141592653589793;
const double ans = 1e-12;
double f(double a, double b, double c, double d, double x) {
return a * x * x * x + b * x * x + c * x + d;
}
double solve(double a, double b, double c, double d, double l, double r) {
double mid;
while (r - l > ans) {
mid = (l + r) / 2;
if (f(a, b, c, d, l) * f(a, b, c, d, mid) <= 0)
r = mid;
else
l = mid;
}
return (l + r) / 2;
}
int main() {
double a, b, c, d;
cin >> a >> b >> c >> d;
for (int i = -100; i < 100; i++) {
double l = i, r = i + 1;
double y1 = f(a, b, c, d, l), y2 = f(a, b, c, d, r);
if (abs(y1) < ans) {
printf("%.2lf ", l);
