Reputation: 1229
I wrote a recursive function in C to reverse an integer (123 -> 321) which worked fine when I ran it on my Mac, but behaves strangely when my instructor ran it on her computer running Windows.
int rev(int num)
{
int base;
if (num < 10) return (num);
base = pow(10,(int)log10(num));
return(rev(num/10)+num%10*base);
}
For example, on OSX calling rev(8765) returns 5678, On Windows, rev(8765) returns 5672. I don't have access to a Windows machine to try to run the program in debug mode, so I've been having a hard time trying to guess what the issue is. I would greatly appreciate any insight!
Environment:
I am using using OSX 10.8 and GCC 4.2. I'm pretty sure my instructor is using MinGW as her compiler.
Upvotes: 4
Views: 505
Reputation: 106297
pow
and log10
are not required to be correctly rounded; the results produced by them can and will differ between platforms, even for cases that “should be” exact like in your example. In this case, OS X produces a more accurate result than Windows, which results in errors that show up only in the Windows output.
A much better solution would be to use repeated division and multiplication by 10 in integer, and not use floating-point at all (there is a very clean recursive solution similar to yours, without requiring that you compute base
).
As an aside, a mini-rant: It’s shameful that so many math libraries do not correctly handle small powers of ten and two in log10
, log2
, exp2
and pow
. It is not hard to design these functions such that they do the “right thing” for these cases, and it can be done without adversely affecting performance of other cases. While it is not required by the standard, it is a simple thing to do and it helps to save inexperienced programmers from (exceptionally common) errors like this one.
Upvotes: 7