Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   pow() and modulus trouble (http://www.go4expert.com/forums/pow-modulus-trouble-t696/)

akidamo 7Apr2006 06:49

pow() and modulus trouble
Hi I am programming in C,

and when I do a pow function such as num = pow(28,7);

If num is a float or a double, the correct answer is achieved, but if it is an int or a long, num is assigned an incorrect answer.

Which gives me a problem because I then what to do num%33.

Like I said if I do it, when num is an int, the answer is incorrect.
and if I keep num as a double or float, I get the error:
illegal use of floating point in function.....

Is there anyway to overcome this? It is driving me mad!! :eek:

coderzone 7Apr2006 08:04

Re: pow() and modulus trouble
Its not the problem with the pow but its just long size is not big enough to hold the data.

long iTemp = (long)pow(28,7);

This should avoid all the errors and warning but the out put is not correct because the actual output is 13492928512 which is more than 2^32.

akidamo 7Apr2006 09:07

Re: pow() and modulus trouble
ahh thanks anyway, I guess there is nothing I can really do then to get the correct answer.

akidamo 7Apr2006 09:44

Re: pow() and modulus trouble
actually I found a way to do it :) ty

coderzone 7Apr2006 10:44

Re: pow() and modulus trouble
Why dont you share that with us.

akidamo 7Apr2006 12:01

Re: pow() and modulus trouble
Sorry! of course, its a bit long, but I got the answer I needed. Just a bit of maths.

Instead of doing modulus 33...

I used a float, say float num1, and found pow(28,7)
I then divided it by 33,
I then assigned this answer to a long/int, which automatically trunicates it, say long num2
I then again assigned it back to a float, and multiplied this float by 33. say float num3
Then i did num1 - num3
which give me the same answer as pow(28,7)%33 should have given me.

Not the best at explaining! :)

All times are GMT +5.5. The time now is 07:11.