[英]How come this function doesn't return 0?
我正在研究 C 和遞歸函數,我寫了一個遞歸 function 來確定給定的字符串是否是回文。
#include <stdio.h>
int testPalindrome(char str[], size_t, size_t);
int main() {
int x;
char string[6] = "rpdar"; // palindrome "radar" for test
x = testPalindrome(string, 4, 0);
printf("Palindrome: %d\n", x);
}
int testPalindrome(char str[], size_t sizeMax, size_t sizeMin) {
if (sizeMax > sizeMin) {
if (str[sizeMax] != str[sizeMin]) {
return 0;
} else {
return testPalindrome(str, sizeMax - 1, sizeMin + 1); // the function compares the first letter with the last, the second with the penultimate and so on
}
}
return 1;
}
如果是,則程序打印1
,否則打印0
。 它可以工作,但我想知道如果我在遞歸調用之前不寫return
, testPalindome
怎么不返回 0:
int testPalindrome(char str[], size_t sizeMax, size_t sizeMin) {
if (sizeMax > sizeMin) {
if (str[sizeMax] != str[sizeMin]) {
return 0;
} else {
testPalindrome(str, sizeMax - 1, sizeMin + 1);
}
}
return 1;
}
我認為我無法理解問題在於遞歸調用的工作原理。
在我看來,在后一種情況下, testPalindrome
有一次假定值為0
,但由於在調用之前沒有return
,它必須完成 function 中留下的任何其他指令,因此最終假定值為1
。 那有意義嗎?
如果您的第一個和最后一個字符不相同並且您的 str 長度 > 1 ,您將得到 0 ,否則它將返回 1。
試試你的 function:
"aba" 將返回 (1)
"abc" 將返回 (0)
"abca" 將返回 (1):這是您的代碼問題
您的 function 工作但不是所有的可能性。
使用您所做的不同測試來測試您的代碼非常重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.