开发者

why use int error,but long long right

开发者 https://www.devze.com 2023-03-07 04:57 出处:网络
int c; long long sum=0; sum+=c*(c-1)/2; when c=100000,why sum can\'t get the right answer? should I write
int c;
long long sum=0;
sum+=c*(c-1)/2;

when c=100000,why sum can't get the right answer? should I write sum+=(开发者_Go百科long long)(c*(c-1)/2);


int here is 32-bit I assume - 100000 squared (10E9) exceeds the maximum range for an int resulting in an overflow. The below would work - casting the first instance of c to long long will mean that the rest of the expression will be "long long compatible".

sum+=((long long)c*(c-1)/2);


Because it is using c as an int in the calculations, and widening it when it's stored.

You need to cast one of the c's to a long long before multiplying.

Also, I suggest you look into using int64_t in place of long long so that you can get the actual type/size you want no matter what (see stdint.h for the various identifiers).


In your question c is declared as integer. so it crosses the limit of integer itself in the expression c*(c-1). so overflow occurs.before it gets implicitly converted into long long.Thats the reason behind UB.

whereas when u implicitly converted it into long long u will ger the right answer...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号