gpt4 book ai didi

c - 陷入 C 语言的 Loop Collat​​z 猜想尝试

转载 作者:行者123 更新时间:2023-11-30 16:56:49 24 4
gpt4 key购买 nike

我的代码中存在逻辑缺陷,我似乎无法将 2^31 − 1 作为输入传递。这是我的代码片段。

#include <stdio.h>
int main() {
long input = 0;
long temp = 0;
int count = 0;
printf("Enter a positive integer ( or 0 to quit): ");
scanf("%ld", &input);
if(input == 0)
{
printf("Quit.");
}
else
{
temp = input;
while (temp != 1)
{
if(temp %2 ==0)
{
temp = temp/2;
count++;


} else
{
temp = 3*temp + 1;
count++;
}

}
return 0;
}

我尝试将输入的大小更改为 long => long long ,但在调试后它仍然卡在该区域内。请提供一些反馈,谢谢!

最佳答案

假设您的系统有 64 位 long,然后将其更改为与 unsigned long 一起使用,包括 scanf(),似乎工作正常:

#include <stdio.h>
#include <assert.h>

int main() {
unsigned long input;
assert(sizeof(input) * 8 >= 64);

while (1) {
printf("Enter a positive integer (or 0 to quit): ");
(void) scanf("%lu", &input);

if (input == 0) {
break;
}

unsigned int count = 0;

while (input != 1) {
if (input % 2 == 0) {
input /= 2;
} else {
input = 3 * input + 1;
}
count++;
}

printf("%d\n", count);
}

printf("Quit.\n");

return 0;
}

使用

> ./a.out
Enter a positive integer (or 0 to quit): 2147483647
450
Enter a positive integer (or 0 to quit): 0
Quit.
>

否则,寻找其他 64 位类型(long long?)来使用。 Python 的工作方式是因为它具有无限大的整数。

关于c - 陷入 C 语言的 Loop Collat​​z 猜想尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39796706/

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