c - main 函数不调用 collatzSequencer 函数
问题描述
我目前正在为大学一年级的计算机课程做一个项目。话虽如此,我并不是在寻求答案,而是在寻求更多建议。为了开始这个项目,我决定创建一个名为 collatzSequencer 的函数,它接受一个参数类型 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 在调用它时甚至没有运行 collatzSequencer 函数。虽然我是初学者,但我觉得我有足够的知识能够在 48 行代码中找到问题,但是我在这里找不到问题。有人有想法么?
解决方案
您正在检查三种情况:
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 语句捕获。
推荐阅读
- flutter - 使用 Widget 列表动态更改 Scaffold 的主体
- mysql - MySQL JSON 查找多个值
- c# - 为什么我可以在没有 INotifyPropertyChanged 的情况下更新 UI
- javascript - 如何通过键将对象转换为对象数组?
- javascript - 反应来自虚拟 DOM 的元素与来自 HTML DOM 的元素
- javascript - 在特定时区将字符串更改为日期
- python - 你可以禁用输入()上的粘贴吗?
- r - Flexdashboard DT 数据表未填充面板高度
- java - Apache poi 循环引用?
- python - 用 Pyautogui 按住鼠标右键