# Strange behavior converting data types?

I’m writing a function to convert a number to trinary.
The function receives an integer and puts appropriate values into a global array of integers. I’ve written three different functions that I think should do the same thing, but they don’t for the numbers 26 and 27. I’d like help figuring out why. I suspect it has something to do with data types.

First, the function that works.
void inTrinary(int n){
ledState = (int(n/(pow(3,0)))%3);
ledState = (int(n/(pow(3,1)))%3);
ledState = (int(n/(pow(3,2)))%3);
ledState = (int(n/(pow(3,3)))%3);
ledState = (int(n/(pow(3,4)))%3);
ledState = (int(n/(pow(3,5)))%3);
}

if n = 26, then ledState = {2, 2, 2, 0, 0, 0} and
if n = 27, then ledState = {0, 0, 0, 1, 0, 0}

Second, one function that doesn’t work.
void inTrinary(int n){
for (int j = 0; j < 6; j++){
ledState[j] = (int(n/(pow(3,j)))%3);
}
}

for this function, if n = 27, then ledState unfortunately = {0, 2, 0, 1, 0, 0}

Third, another function that doesn’t work.
void inTrinary(int n){
for (int j = 0; j < 6; j++){
ledState[j] = ((n/int(pow(3,j)))%3);
}
}

for this function, if n = 26, then ledState unfortunately = {2, 2, 2, 1, 0, 0}

If someone could explain to me why there’s this difference, I’d greatly appreciate it. Thank you.

From what I have read elsewhere, it seems that pow() does not give exact results, and that is causing the problem. Or maybe it's floating-point division, I don't know.

``````int myPow(int x, int y) {
// raises x to the power of y
int z = 1;
while (y--) {
z *= x;
}
return z;
}
``````

Then, everywhere your code uses pow(), change it to myPow(), and everything should be OK. (Untested code, please let me know if any problems.)

You probably should avoid pow() altogether, something more efficient like:

``````void inTrinary(int n)
{
for (int j = 0; j < 6; j++)
{
ledState[j] = n % 3 ;
n /= 3 ;
}
}
``````