除以2和Sigsegv误差时按位移位的奇怪行为

use*_*260 0 c++ bit-manipulation bit-shift bitwise-operators

我正在写一段代码,我必须执行2的除法.以下代码行给出了正确的输出

ans = ans + ((long long)cnt * (cnt-1))/2;
Run Code Online (Sandbox Code Playgroud)

但是,当我改变它

ans = ans + ((long long)cnt * (cnt-1)) >> 1;
Run Code Online (Sandbox Code Playgroud)

上面的代码有什么问题

在我的设置中,值永远不会消极

这是代码

#include<bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
int s[1000000];
int main(){_
int t;
cin>>t;
while(t--){
    int n,i,z,sum=0,p,cnt=0;
    unsigned long long int ans=0;
    cin>>n;
    for(i=0;i<n;i++){
        cin>>z;
        sum+=z;
        s[i]=sum;
    }
    sort(s,s+n);
    i=0;
    while(i<n){
        p=s[i];
        cnt=0;
        while(s[i]==p){
            cnt++;
            i++;
        }
        ans=ans+((unsigned long long)cnt*(cnt-1))>>1;
    }
    cnt=0;
    for(int i=0;i<n && s[i]<=0;i++){
        if(s[i]==0){
            cnt++;
        }
    }
    ans+=cnt;
    cout<<ans<<"\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

输入1 4 0 1 -1 0

输出为4但是它应该是6

此外,代码为高输入提供Sigsegv错误

1 <= T <= 5

1 <= N <= 10 ^ 6

-10 <= z <= 10

Dan*_*rey 6

运算符>>优先级低于+(当然/),因此您编写了相当于:

ans = ( ans + ((long long)cnt * (cnt-1)) ) >> 1;
//    ^--- note these -------------------^
Run Code Online (Sandbox Code Playgroud)