why overflow happens on calculation depending on the data type when the type where the value is being assigned can hold it

前端 未结 5 2032
别那么骄傲
别那么骄傲 2021-01-28 02:10

Earlier I came up with something, which I solved, but it got me later let\'s take a look at a similar example of what I was on:

int b = 35000000; //35million
int         


        
5条回答
  •  遥遥无期
    2021-01-28 02:35

    In C++, there are programming elements called "literal constants".

    For example (taken from here):

    157 // integer constant

    0xFE // integer constant

    'c' // character constant

    0.2 // floating constant

    0.2E-01 // floating constant

    "dog" // string literal

    So, back to your example, 100 * 30000000 is multiplying two ints together. That is why there is overflow. Anytime you perform arithmetic operations on operands of the same type, you get a result of the same type. Also, in the snippet unsigned long a = 30000000;, you are taking an integer constant 30000000 and assigning that to the variable a of type unsigned long.

    To get your desired output, add the ul suffix to the end: unsigned long n = ( 100ul * 30000000ul ) / b;.

    Here is a site that has explanations for the suffixes.

    why /b when b is unsigned long is still an interesting question

    Because 100 * 30000000 is performed before you divide by b and the operands are both of type int.

提交回复
热议问题