Question

I am currently learning C++. I was trying to compute power of an integer using the expression:

val=10^1;

Instead of expected answer 10, the result was 11. I have fixed the problem by using pow function of math.h library but I am wondering why this statement is giving me the wrong result.

Était-ce utile?

La solution 2

That's the bitwise exclusive-or operator, not power. In binary:

10 = 1010
 1 = 0001
val= 1011 = 11 in decimal

Autres conseils

No! Do you think that is the power? Don't forgot this (In C++ and some of the programming languages): enter image description here

Be sure to read this:


A bitwise XOR takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. In this we perform the comparison of two bits, being 1 if the two bits are different, and 0 if they are the same. For example:

    0101 (decimal 5)
XOR 0011 (decimal 3)
  = 0110 (decimal 6)

The bitwise XOR may be used to invert selected bits in a register (also called toggle or flip). Any bit may be toggled by XORing it with 1. For example, given the bit pattern 0010 (decimal 2) the second and fourth bits may be toggled by a bitwise XOR with a bit pattern containing 1 in the second and fourth positions:

    0010 (decimal 2)
XOR 1010 (decimal 10)
  = 1000 (decimal 8)

This technique may be used to manipulate bit patterns representing sets of Boolean states.

Source: Wikipedia

In C and C++, 10^1 is 10 XOR 1, not 10 to the power of 1.

^ is the binary XOR operator in C++:

10 ^ 1 = 

   00001010
^  00000001
=  --------
   00001011 = 11

Because ^ is the exclusive or operator and not the exponentiation operator. Basically, because the last bit of 10 in binary is 0, by applying exclusive or of 1 the last bit gets converted to 1 because it is different than 0.

Because in C++ there is no power operator: ^ is a XOR.

1010 is 10102 in binary; 110 is 00012. XORing them together gives 10112, which is 1110.

If you would like to obtain 10n, use the pow function from <cmath> header:

val=pow(10, 1);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top