|
发表于 2023-12-20 17:55:58
From FishC Mobile
|
显示全部楼层
|阅读模式
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这段c++代码为什么编译错误
#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
using namespace std;
int L, M, N;//L为距离,N为岩石数目,M为可移去数
int A[50005];
int x;
bool check(int mid)
{
int now = 1;
int nex = 1;
while(nex <= N + 1)
{
nex++;
if (A[nex] - A[now] < mid)
{
nex++;
x++;
}
else
{
now=nex;
}
if (x > M)
{
return 0;
}
}
if (x > M)
{
return 0;
}
else
{
return 1;
}
}
int main()
{
cin>>L>>N>>M;
A[N + 1] = L;
for (int i = 1; i <= N; i++)
{
cin>>A[i];
}
int l=0,r=M;
while (l < M)
{
mid=(l+r)/2;
if (check(mid))
{
l = l + 1;
}
else
{
r = r - 1;
}
}
cout<<mid<<endl;
return 0;
}
这段C++代码编译不通过的原因是缺少了必要的头文件。你需要包含iostream头文件来使用输入输出流,以及cmath来使用数学函数等。此外,代码中的while循环控制条件错误,逻辑上存在错误的括号配对,导致编译错误。
以下是修复后的代码:
- #include <iostream>
- #include <cmath>
- using namespace std;
- int L, M, N; // L为距离,N为岩石数目,M为可移去数
- int A;
- int x;
- bool check(int mid)
- {
- int now = 1;
- int nex = 1;
- while (nex <= N)
- {
- if (mid >= x) // 此处是大于等于号
- {
- now++;
- mid -= x;
- }
- else
- {
- nex++;
- mid = L - x;
- }
- x = L - mid;
- if (now > M)
- {
- return false;
- }
- }
- if (x > M)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- int main()
- {
- cin >> L >> N >> M;
- A = L;
- for (int i = 1; i <= N; i++) // 此处是小于等于号
- {
- cin >> x;
- }
- int l = 0, r = M;
- int mid; // mid需要提前定义
- while (l < r) // 此处是小于号
- {
- mid = (l + r) / 2;
- if (check(mid))
- {
- l = mid + 1; // 对应的左边界改为mid+1
- }
- else
- {
- r = mid; // 对应的右边界改为mid
- }
- }
- cout << l - 1 << endl; // 输出结果
- return 0;
- }
复制代码
希望对你有所帮助!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
|