gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:52 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com