【问题标题】:Writing a txt file while running some calculations在运行一些计算时编写一个 txt 文件
【发布时间】:2019-10-30 19:48:07
【问题描述】:

我正在尝试创建一个在 txt 文件中输出Collatz conjecture 的结果的程序。但是,当我尝试使用大数字(例如 1,000,000)时,它无法正常工作并且总是停在 113383。

代码如下:

int n, count, number, mayor, masvueltas, top;
char c = '@';
freopen("output MILLION.txt", "w", stdout);
count = 0;
number = 1;
mayor = 0;
masvueltas = 0;
while(number != 1000000) {
    printf("\n%d did ", number);//this will say that number did COUNT loops
    n = number;
    while (n != 1) {
        if (n % 2 == 0) {
            n = n / 2;
            count++;
        }
        else {
            n = 3 * n + 1;
            count++;
        }
    }
    printf(" %d saltos.\n", count);//Here continoues the sentence
    char graf[count];//creates an array to print the @ character COUNT times
    for (int i = 0; i < count; i++) {
        graf[i] = c;
        printf("%c", graf[i]);
    }
    if(masvueltas < count) {
        masvueltas = count;
        mayor = number;
    }
    number++;
    count = 0;
}

另外,如果您知道如何在 txt 文件中打印 ASCII 字符 219,块,那就太好了。不重要,所以我有一个更干净的 txt 文件。

【问题讨论】:

  • graf 的目的是什么?您不需要数组来打印count at 标志,只需在循环中打印putchar('@')printf("@")
  • 您是否尝试过为候选人使用更大的数据类型,例如long long int?从大约 1,000,000 开始,它不必连续多次使用路径 n=(3*n)+1; 即可打破存储范围。
  • 哦,是的。你是对的@WeatherVane。用 long long int 工作。有没有办法修改它的大小或默认限制?
  • ...确实,1001063 在 149 次迭代后确实打破了 int 限制。
  • 好吧,你可以在n * 3 + 1之前通过与安全的最大值进行比较来测试它是否会破坏数据类型。例如,int 的最大安全值为(INT_MAX - 1) / 3

标签: c windows loops collatz


【解决方案1】:

发生这种情况是因为number = 113,383 在 119 次计数后计算达到 827,370,449 的值,下一次计数最大值为 2,482,111,348,大于maximum value of int variable 2,147,483,647,这使得n 的值变为负数, -1812855948,循环未能达到 1。您应该使用long long n 来获得您想要的结果。我还建议您使用for 循环而不是while 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    相关资源
    最近更新 更多