Why use int error, but long long right

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

when c = 100000, why can't the sum get the right answer? I have to write sum + = (long long) (c * (c-1) / 2);

+3
source share
3 answers

intHere, I assume that the 32-bit value is 100000 squared (10E9) exceeds the maximum range for int, which leads to overflow. Below will work: casting the first instance cin long longwill mean that the rest of the expression will be "long long compatibility."

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

Because it uses cboth intin calculations and expands it when it is stored.

, , c long long.

, int64_t long long, /, , , (. stdint.h ).

+1

In your question, c is declared as a whole. therefore, it crosses the limit of the whole in the expression c * (c-1). therefore, overflow occurs. Before it is implicitly converted to long long.Thats the reason for UB.

then when u implicitly converted it to long long u, you get the correct answer ...

+1
source

All Articles