繁体   English   中英

这个 function 怎么不返回 0?

[英]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 它可以工作,但我想知道如果我在递归调用之前不写returntestPalindome怎么不返回 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM