此代码在代码块中完美运行,但在 ideone.com 时出现运行时错误

This code is running perfectly in codeblocks but giving a runtime error on ideone.com

本文关键字:代码 com ideone 运行时错误 但在 完美 运行      更新时间:2023-10-16
int main()
{
    long int n,x,cost[100];
    cin>>n>>x;
    for(int i=0;i<n;i++)
        cin>>cost[i];
    int i=0,flag=0,s=0,first;
    first=cost[0];
    while(i<n)
    {
       s+=cost[i];
       if(s>x){
           s-=first;
           first++;
       }
       if(s==x)
       {
           flag=1;
           break;
       } 
       i++;
    }
    if(flag==0) cout<<"no";
    else cout<<"yes";
}

Ideone demo

这段代码是来自hackerearth的问题。问题的名称是"Prateek和他的朋友"请帮忙。

我不确定这是否是您唯一的错误,但您应该始终确保已将整数变量分配给(除非您最终不使用它们(在这种情况下,明智的默认值可能是 long int n = 0, x = 0 .

此外,如果cin>>n无法从流中读取(由于 EOF(,您将无法正常工作,您可能应该在执行读取后检查它是否成功,使用 cin.fail() ,如果它返回比上一个操作(或之前的操作(失败true

我实际上不记得以前处理过流读取失败的可能性,所以我可能错了/错过了一些东西