gpt4 book ai didi

计算从 1 到 n 的素数——崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:16 25 4
gpt4 key购买 nike

我用 C 编写了一些代码来计算从 1 到 n 的所有质数(n 是用户输入的)。

由于为其中一个实际算法赋予形式来执行此操作有点超出我的技能范围,因此我决定通过蛮力来完成:

编辑:img(还不能发布,少于 10 个代表 http://i44.tinypic.com/332t9uv.jpg)这就是我实际编码的方式,不知道为什么我的代码格式在发布时被改变了,抱歉。

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n, i = 1, x = 1;
printf("Porfavor escriba el numero: ");
scanf(" %d", &n);
while (i != n)
{
x = 1;
while (x <= i)
{
if (x % i == 0)
{
continue;
++x;
if (x == i && x % i != 0)
printf("%d ", x);
}
}
i++;
}
return EXIT_SUCCESS;
}

一切顺利并要求输入,但在用户输入 n 之后程序崩溃了,我有点困惑为什么会这样。

任何帮助将不胜感激!谢谢!

编辑:使它们不为 0 后,它仍然不起作用,不再崩溃,但它从不计算任何东西,我必须手动退出程序。知道如何解决这个问题吗?

最佳答案

如果你以后遇到这样的问题,你可以通过在 gdb 中运行你的程序来轻松地跟踪它们:

# compile:
gcc -Wall -ggdb main.c
# run in gdb:
gdb --args ./a.out
# ... lots of notes of gdb ...
> run
Porfavor escriba el numero: 7
# program crashes at some point
# let's have a look at it with a backtrace
# (it will also print the line where the program crashed)
> bt

关于计算从 1 到 n 的素数——崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9514164/

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