c - 我无法让这段代码正常运行。显示 1 到 100 之间的质数

标签 c

程序: 我必须编写一个程序来显示 1 到 100 之间的所有素数。

历史: 我编写了一个程序,要求用户输入一个数字,告诉他这是否是素数,如果不是,程序会显示其因子。

困惑: 但我不明白为什么这个程序(显示从1到100的质数)不能正常运行。

任何帮助将不胜感激。

//pre-processor directives
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

//global variables/declarations
int factors=0;
int checkifprime(int num);

//main function - start
int main()
{
    //declaring loop variable
    int c;
    for (c=1;c<=100;c++)
    {
        if (c==1 ||c==2)
        {
            printf("\n%d is a prime number",c);
        }
        else
        {
            factors = 0;
            printf("error ");
            checkifprime(c);
            printf("error ");
            if (factors=0)
            {
                printf("\n%d is a prime number",&c);
            }
            else
            {
                printf("\n%d is NOT a prime number",&c);
            }
        }
    }

}

int checkifprime(int num)
{
    int i;
    if (num>0 && num<2147483640)
    {
        i = num-1;

        for (i;i>1;i--)
        {
            if (num%i==0)
            {
                factors=factors+1;

                printf(" %d",i);
            }
        }
    }

    //program finished
    getch();
    return 0;
}

最佳答案

其中有一个小但很重要的拼写错误。如果您打开所有警告,您就会捕获它,因此下次:打开编译器提供的所有警告。经过一些额外的清理以摆脱 Windows 独有的东西:

//pre-processor directives
#include <stdio.h>
#include <stdlib.h>

//global variables/declarations
int factors = 0;
int checkifprime(int num);

//main function - start
int main()
{
//declaring loop variable
  int c;
  puts("1 is NOT a prime number");
  for (c = 2; c <= 100; c++) {
    if (c == 2 || c == 3) {
      printf("%d is a prime number\n", c);
    } else {
      factors = 0;
      checkifprime(c);
      fputc('\n',stdout);
      // you had a typo here "=" instead of "=="
      if (factors == 0) {
        printf("%d is a prime number\n", c);
      } else {
        printf("%d is NOT a prime number\n", c);
      }
    }
  }
  exit(EXIT_SUCCESS);
}

int checkifprime(int num)
{
  int i;
  if (num > 0 && num < 2147483640) {
    for (i = num - 1; i > 1; i--)
    {
      if (num % i == 0) {
        factors = factors + 1;
        printf(" %d", i);
      }
    }
  }
//program finished
  return 0;
}

它仍然不理想,但至少它可以工作并且您可以在它的基础上进行构建。

关于c - 我无法让这段代码正常运行。显示 1 到 100 之间的质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39946336/

相关文章:

c - 如何使 switch 语句正确循环?

c - 使用 malloc 函数的空间复杂度

c - pthreads/等待(&状态)

c - C中结构的内存分配

c - 如何使用宏来调用函数?

c - 如何构建灵活的代码层次结构

c - 使用 GDB 更改 for 循环条件?

c - 你如何在 C 中定义一个接受结构指针参数的宏?

c - 无法循环遍历c pos中的数据

c - 如何获取*不*存在的文件或目录的绝对路径?