首页 > 解决方案 > main 函数不调用 collat​​zSequencer 函数

问题描述

我目前正在为大学一年级的计算机课程做一个项目。话虽如此,我并不是在寻求答案,而是在寻求更多建议。为了开始这个项目,我决定创建一个名为 collat​​zSequencer 的函数,它接受一个参数类型 int。

这是我的函数原型:

int collatzSequencer(int);

这是我的函数定义:

int collatzSequencer(int n) {
    int stepCounter = 0;
    if (n % 2 == 0) {
        stepCounter += 1;
        collatzSequencer(n / 2);
    }
    else if (n % 2 == 1) {
        stepCounter += 1;
        collatzSequencer((3 * n) + 1);
    }
    else if (n == 1) {
        printf("%d\n", n);
        printf("%d\n", stepCounter);
        return 0;

这是我在主函数中调用该函数的地方:

int main(int argc, char* argv[]) {
    int num = 5;
    collatzSequencer(num);
    return 0;
}

当我运行我的程序时,什么也没有发生,我退出代码 0。我尝试调试我的程序,我发现由于某种原因,我的 IDE 在调用它时甚至没有运行 collat​​zSequencer 函数。虽然我是初学者,但我觉得我有足够的知识能够在 48 行代码中找到问题,但是我在这里找不到问题。有人有想法么?

标签: cfunctionrecursiondefinitioncollatz

解决方案


您正在检查三种情况:

n % 2 == 0 (eg. n is Even)
n % 2 == 1 (eg. n is Odd)
n == 1  (eg. n is exactly ONE; this is also the only if-statement with a return)

除了: value1是一个奇数,由第二种情况捕获。

您的代码永远不会遇到这种n==1情况,因为当n为 1 时,它总是会首先被奇值 if 语句捕获。


推荐阅读