我正在尝试完成发现的 Project Euler 问题 here.出于某种原因,我确定给定字符串是否为回文的函数认为“989010”是回文。有趣的是,如果我直接将该字符串输入回文函数,它就能正常运行。这是我的代码(我是新手,很抱歉格式错误!):
bool palindrome(char pal[]);
int main(){
int i = 0;
int j = 0;
int k = 0;
int numdig = 0;
int numtest = 0;
for(i = 999; i > 99; i--){
for(j = 999;j > 99; j--){ //for loops multiply all 3 digit numbers
k = i * j;
numtest = k;
numdig = 0; //this part takes care of determining the number of digits
while(numtest > 0){
numdig++;
numtest /= 10;
}
char string[numdig + 1];
itoa (k,string,10); //itoa turns an integer into a string w/ null char.
if( palindrome(string)){
printf("It is a palindrome: %i\n",k);
system("pause");
return 0;
}
}
}
return 0;
}
bool palindrome(char pal[]){
int half = (sizeof(pal) - 1)/2; //this divides the string in half
int forward = 0;
int backward = sizeof(pal)-2;
while(forward < half && backward > 0){ //compares the charactera in the front
if(pal[forward] == pal[backward]){ //to the chars in the back until they
forward++; //meet in the middle
backward--;
}
else{
return false;
}
}
return true;
}
最佳答案
参数的sizeof
不是指向的字符串的字符数,因为参数尽管有声明形式,但只是一个指针而不是数组。请改用 strlen
并注意它在返回值中不包含终止符 \0
(与 sizeof
应用于字符串数组时相反) ).
字符串 "989010"
如果只取它的前 3 个字符 "989"
,它看起来像一个回文。由于应用于指针的 sizeof
在您的机器上产生 4
,因此仅检查前三个字符。
关于程序的组成部分工作,当放在一起时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3191787/