我已经使用此功能来检查我的字符串是否是回文。如果是,它将打印它,但是当字符串不是回文时,它不会打印任何内容
bool is_palindrome(char cad[]){
bool is = false;
int size, i;
size = 0;
i = 0;
while(cad[i] != '\0'){
i++;
size++;
}
i = 0;
while(cad[i] != '\0'){
if(cad[i] == cad[size - 1]){
i++;
size--;
is = true;
}else{
is = false;
}
}
if(is == true){
printf("IS PALINDROME\n");
}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;
}
答案 0 :(得分:3)
您有一个无限循环。在第二个while()中,如果单词不是回文,它将进入else
条件,并且您不会递增i
。因此循环永远不会退出!
一旦找到一个不匹配的字母,您就可以简单地从循环中break
退出,因为您知道该单词不是回文。像这样:
bool is_palindrome(char cad[]){
bool is = false;
int size, i;
size = 0;
i = 0;
while(cad[i] != '\0'){
i++;
size++;
}
i = 0;
while(cad[i] != '\0'){
if(cad[i] == cad[size - 1]){
i++;
size--;
is = true;
}else{
is = false;
break;
}
}
if(is == true){
printf("IS PALINDROME\n");
}else if(is == false){
printf("IT ISN'T PALINDROME");
}
return is;
}
您甚至可以进一步简化它,例如:
is = true;
while(cad[i] != '\0') {
if(cad[i] != cad[size - 1]){
is = false;
break;
}
i++;
size--;
}