3
short sho1, sho2;
printf("Enter two shorts.\n");
scanf("%hd %hd", &sho1, &sho2);
printf("%hd^%hd is %hd.\n", sho1, sho2, sho1^sho2);

When I enter '2 2', I get this output:

2^2 is 0.

How come? I'm using the MinGW GCC compiler in Eclipse, in case that's of any importance.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
Pieter
  • 31,619
  • 76
  • 167
  • 242
  • 7
    Just as a sidenote, if you simply want the square of an integer, don't use pow() but x*x. This saves you some floating point conversions. It seems obvious, but sometimes people tend to forget that. Including me when I looked the first time for a power operator :) – quinmars Jan 08 '10 at 15:17

6 Answers6

18

^ is not the mathematical power operator in C, it's the bitwise exclusive-OR operator. You probably want the pow function, which takes two doubles.

ChrisInEdmonton
  • 4,470
  • 5
  • 33
  • 48
  • 8
    You can apply `^` to doubles, in which case the complier C truncates the values then exclusive ORs the bit patterns of the corresponding ints. When working on anti-collision algorithms for UAVs (uninhabited air vehicles), some sample code from NASA had an optimisation which never happened as it calculated squares using `dist^2`. (gcc 4 doesn't truncate; this was a few years ago on windows ) – Pete Kirkham Jan 08 '10 at 14:01
  • Oooh, +1 for very interesting comment. – ChrisInEdmonton Jan 08 '10 at 16:07
7

You aren't using the operator that you think you're using.

^ is the bitwise XOR operator.

You are looking for the pow function.

Prototype: double pow(double b, double p);

Header File: math.h (C) or cmath (C++)

Explanation: This function raises b to the p power.

Wikipedia has a useful list of operators that are valid in C and C++.

Community
  • 1
  • 1
Bob Cross
  • 22,116
  • 12
  • 58
  • 95
3

The ^ operator is not the power operator; it is the bitwise XOR operator. For the power operator you want to use the function pow declared in math.h. Thus:

pow(2.0, 2.0)

will return 4.0 (intentionally emphasizing that parameters and return value are doubles).

Note further that pow returns a double so you will have to change the format specifier to %g:

printf("%hd^%hd is %g.\n", sho1, sho2, pow((double)sho1, (double)sho2));
jason
  • 236,483
  • 35
  • 423
  • 525
3

There is no "power" operator in C - ^ is the XOR (bitwise exclusive OR) operator

Sam Post
  • 3,721
  • 3
  • 17
  • 14
2

You can use the pow() function in C.

pow(base, exponent);

It's in the math.h header file.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
1

In c ^, is the exclusive or operator. In order to do powers, you have to use the pow function.

pow(2,2)

Brian Young
  • 1,748
  • 13
  • 11