简体   繁体   中英

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

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

This code is a problem from hackerearth. Name of the problem is 'Prateek and his friends' Please help.

I am not sure if this is your only error, but you should always ensure that integer variables have been assigned to, (unless you don't end up using them) In this case a sensible default might be long int n = 0, x = 0 .

In addition, cin>>n will not work properly if it can't read from the stream (due to EOF) you should probably check after doing a read that it succeeded, use cin.fail() , if it returns true than the previous operation (or a one before that) failed.

I don't actually recall dealing with the possibility of a stream read failing before, so I may be wrong/missed something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM