Now, I'm doing some problems on ProjectEuler.net, and this is the code I write for Problem #4:
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int isPalindrome(int num)
{
int length = floor(log10(abs(num))) + 1;
int index = 0;
int firstChar, lastChar;
while (index <= (length / 2)) {
firstChar = (num % (int)pow(10, length - index)) / pow(10, length - 1 - index);
lastChar = (num % (int)pow(10, (index + 1))) / (pow(10, index));
if (firstChar != lastChar) {
return 0;
}
index++;
}
return 1;
}
int main(int argc, char *argv[])
{
clock_t begin, end;
double time_spent;
int result = 0;
int x, y;
printf("Is 998001 a palidrome? %d\n", isPalindrome(998001));
printf("Is 987789 a palidrome? %d\n", isPalindrome(987789));
printf("Is 884448 a palidrome? %d\n", isPalindrome(884448));
/* clock start */
begin = clock();
for (x = 999; x > 99; x--) {
for (y = 999; y > 99; y--) {
if (isPalindrome(x * y) && x * y > result) {
result = x * y;
printf("Found palindrome: %d\tX: %d\tY: %d\n", result, x, y);
}
}
}
end = clock();
/* clock end */
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("ANSWER: %d\n", result);
printf("ELAPSED TIME: %f\n", time_spent);
return 0;
}
Not beautiful, but it works. When I compile this on GNU/Linux, it works fine. However on Windows 7 64-bit, I get this output:
Expected output:
Here's where it gets weird. If you swap lines 17 and 18 (the ones that start with firstChar and lastChar) it works fine on both Windows and GNU/Linux.
What is going on here? I compiled with mingw32 gcc like this:
gcc -v prob4.c -o prob4.exe -lm
Here's the compiler output: http://pastebin.com/rtarBtNY
Seriously guys what the hell is happening?
The problem with floating points. If you have the following code:
pow(10, 2)
you expect the value returned to be 100. It might be but there's no guarantee. You will get a value close to 100 within some margin of error.
If the value returned is 100+d
(where d
is within the precision) then when that value is converted to an int
you get back 100
. If the value returned is 100-d
then when that value is converted to an int
you get back 99
.
That code shouldn't even compile. You're declaring a function inside of main.
If you move the isPalindrome() function definition outside of main I can verify that it compiles in linux with no errors and no warnings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.