#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的数字的每个数字的Collatz序列。我希望这可行。任何人都可以帮助我让它发挥作用吗?
答案 0 :(得分:1)
您正在混合要打印的序列范围,最大迭代次数和序列中的当前数字。
以下是修复代码的方法:
#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;
}