tags:

views:

328

answers:

7
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.

+7  A: 

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++.

Bob Cross
use pow function from cmath/math.h
Amit Kumar
@Amit - yes, I was looking for a better formatted reference for the pow function. I'd forgotten about the cprogramming.com site.
Bob Cross
+15  A: 

^ 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
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
Oooh, +1 for very interesting comment.
ChrisInEdmonton
+1  A: 

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

pow(2,2)

Brian Young
+3  A: 

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
+2  A: 

You can use the pow() function in C.

pow(base, exponent);

It's in the math.h header file.

Bill the Lizard
+2  A: 

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

Sam Post
A: 

even i got this problem use this type of format :- printf ("2 ^ 2 = %lf\n", pow ( 2 , 2 ) ); it will surely compile as power considers its arguments to be double by default.or use 2.0 and 2.0

arj97