Incorrect product of two INT_MAX numbes in C/C++

余生长醉 提交于 2019-12-10 14:56:02

问题


In my case, product of two INT_MAX numbers is 296447233, which is incorrect.

long long int product = 0;
product = 2137483647 * 2137483647;
printf("product: %lli\n", product);

What I am doing wrong, and how to correct it ?? Thanks !


回答1:


Both of your 2137483647 are of type int. So they stay that type and overflow.

Make them long longs:

product = 2137483647LL * 2137483647LL;

or cast:

product = (long long)2137483647 * 2137483647;



回答2:


Try

product = 2137483647LL * 2137483647LL; 

to ensure that the compile treats the numbers as long long



来源:https://stackoverflow.com/questions/9504477/incorrect-product-of-two-int-max-numbes-in-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!