0

I have a very simple C Program consisting of the following function:

int digit(int num)
{ 
    return num/(10*10*10);
}

calling digit(2345) gives back 2 - as expected.

However, if I write the function in the following way (which - in my opinion - is equivalent!!):

int digit2(int num)
{ 
    return num/(10^3);
}

and then call digit2(2345), this gives back 260 !!! ... This seems totally crazy to me !!! I used the following parameters for compilation in each case: gcc -std=c99 -Wall -Wextra -Wpedantic -Werror

What the hell is going on here???!!!!!

steady_progress
  • 3,311
  • 10
  • 31
  • 62

2 Answers2

3

10^3 means 10 XOR 3, not 10 to the power 3.

To raise a number to some power, use pow(number, power) from math.h. Although in your case this is probably overkill as pow is complicated enough to raise floats to float powers, but you could just multiply the number with itself.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • this is for a university assignment and I'm not allowed to import libraries so I can't use the pow function ... It's not possible to simply use 10*10*10 ... how else can I achieve to get the result of 10 to the power of x in C? Isn't there some operator equivalent to ^in python? – steady_progress Nov 12 '16 at 16:01
  • 1
    @steady_progress, well, Python's power operator is `**`, not `^`: the last one still stands for XOR. In C you either multiply a number by itself, either use `pow`, either write an algorithm yourself. – ForceBru Nov 12 '16 at 16:08
1

10^3 means xor - you need pow function - see https://linux.die.net/man/3/pow

Ed Heal
  • 59,252
  • 17
  • 87
  • 127