从 1 到给定值的 Collat​​z 序列

标签 c collatz

#include <stdio.h>

int main() {
    int rangeValue;
    int x;
    printf("Please input a number to be considered in the range:\n");
    scanf("%d", &rangeValue);
    while (rangeValue != 1) {
        x = rangeValue;
        if ((x % 2) == 0) {
            x = x / 2;
            printf("%d,", x);
        } else {
            x = (3 * x) + 1;
            printf("%d,", x);
       }
       rangeValue--;
    }
    return 0;
}

我的目标是对从 1 到我给 rangeValue 的数字的每个数字执行 Collat​​z 序列。我希望这能奏效。谁能帮我让它工作?

最佳答案

您正在混合要打印的序列范围、最大迭代次数和序列中的当前编号。

修复代码的方法如下:

#include <stdio.h>

int main(void) {
    int rangeValue;
    printf("Please input a number to be considered in the range:\n");
    if (scanf("%d", &rangeValue) != 1)
        return 1;
    // iterate for all numbers upto rangeValue
    for (int n = 1; n <= rangeValue; n++) {
        printf("%d", n);
        for (long long x = n; x != 1; ) {
            if ((x % 2) == 0) {
                x = x / 2;
            } else {
                x = (3 * x) + 1;
           }
           printf(",%lld", x);
        }
        printf("\n");
    }
    return 0;
}

关于从 1 到给定值的 Collat​​z 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46461024/

相关文章:

c - 制作结构数组和整理单词时出现问题

C 编译器断言 : how to dynamically use them wherever the expression is fixed?

javascript - 将数字插入一个数组,然后将该数组插入另一个数组 - JavaScript

clojure - 欧拉项目问题 14 的惰性序列 "Look Ahead"

scheme - 方案中的 Collat​​z 函数

c - 多个共享库使用的变量值

c - linux 机器中的哪个文件代表 gcc 标准 c 库?

c - 从文件中获取数据并在每次新行开始时打印出来

python - While循环语法错误

python - 为什么这个记忆化的 Euler14 实现在 Raku 中比 Python 慢得多?