我做了这个函数来检查我的字符串是否是回文。当它是时,它会打印它,但是当字符串不是回文时,它不会打印任何东西
bool is_palindrome(char cad[]){
bool is = false;
int size, i;
size = 0;
i = 0;
while(cad[i] != ' '){
i++;
size++;
}
i = 0;
while(cad[i] != ' '){
if(cad[i] == cad[size - 1]){
i++;
size--;
is = true;
}else{
is = false;
}
}
if(is == true){
printf("IS PALINDROMEn");
}else if(is == false){
printf("IT ISN'T PALINDROME");
}
return is;
}
我主要是:
int main(){
bool is
is = is_palindrome("ABCDCBA"); //It funtions well
is = is_palindrome("Hello"); //It doesn't funtion
return 0;
}
你有一个无限循环。在第二个while((中,如果单词不是回文,则进入else
条件,并且您不会i
递增。所以循环永远不会退出!
一旦你找到一个不匹配的字母,你可以简单地从这里的循环中break
出来,因为你知道这个词不是回文。喜欢这个:
bool is_palindrome(char cad[]){
bool is = false;
int size, i;
size = 0;
i = 0;
while(cad[i] != ' '){
i++;
size++;
}
i = 0;
while(cad[i] != ' '){
if(cad[i] == cad[size - 1]){
i++;
size--;
is = true;
}else{
is = false;
break;
}
}
if(is == true){
printf("IS PALINDROMEn");
}else if(is == false){
printf("IT ISN'T PALINDROME");
}
return is;
}
您甚至可以进一步简化它,例如:
is = true;
while(cad[i] != ' ') {
if(cad[i] != cad[size - 1]){
is = false;
break;
}
i++;
size--;
}