문제

I am learning about left shift operators and for multiplying a number with 10 I am using this code.

long int num=a<<3+a<<1;

so that no. a first multiplies with 8 and then with 2 and on adding gets a*10 which is stored in num.

But its giving some strange result like for 5 its 2560, for 6 its 6144.

Can anyone please explain whats wrong in that implementation?

도움이 되었습니까?

해결책 2

The format you are using actually goes this way..

num=a<<(3+a)<<1;

make some difference between the two application of shift operators by using parenthesis like

num=(a<<3)+(a<<1);

다른 팁

You have a problem with precedence - the order operators are performed. + binds more tightly than <<, so:

a<<3+a<<1

actually means: a << (a+3) << 1

for 5 that is 5 << 8 << 1 which is 2560 :)

You need: (a<<3) + (a<<1)

See: http://www.swansontec.com/sopc.html for clarification.

What about warning: suggest parentheses around ‘+’ inside ‘<<’

+ is processed before <<.

Use (a<<3)+(a<<1)

<< operator has less precedence than + operator (Thumb rule Unary Arthematic Relational Logical )

so use braces

     int num = (a<<3) + (a<<1);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top