【发布时间】:2019-10-15 18:41:45
【问题描述】:
我想知道我的代码中的错误逻辑在哪里,我怀疑它在于我的循环在打印素数之前完全运行失败,但我似乎无法修复它。我每次都尝试将变量 fcount 重新初始化为 0,但生成的“素数”不正确。我的程序目标是让用户输入数字 N,我可以从 1 循环到 N 并打印其间的所有素数。如果有人能帮助指出我的逻辑错误以及任何可能的解决方案,我将不胜感激。
#include <stdio.h>
int main(void) {
int i,j,n, fcount = 0;
printf("Enter number n:\n");
scanf("%d",&n);
printf("prime numbers are:\n");
for (i=1; i < n; i++)
{
for (j = i; j > 0; j--)
{
if (i%j == 0)
{
fcount++;
// at some point every number will have fcount =2
fcount = 0;
}
}
}
if (fcount == 2)
{
printf("%d\n",i);
}
return 0;
}
【问题讨论】:
-
要重新初始化
fcount,在代码中您希望将其设置为零的位置将其设置为零 - 就在获得i的新值之后和开始计算j是i的因数。然后,要测试一个数字i是否有两个因数,请在完成对因数的计数之后并在继续使用新值i之前测试fcount。
标签: c loops nested-loops