似乎无法找到为什么我的素数程序在重新提示号码后无法正常工作

标签 c

我的程序的质数部分有问题。当我编译并运行我的程序时,第一个数字的质数打印正常,但当重新提示另一个数字时。它通常要么不打印任何数字,要么从某个点向下截断素数。我是编码和这个论坛的新手,所以对于我帖子中的任何格式问题,我深表歉意。

#include <stdio.h>
#include <math.h>
int main(void)
{
    int number, n=1;
    long factorial=1;
    int a=1, b=0,c;
    int q=2, r=2, w=0;
    int prime, count;

    printf("Enter a Number:\n");
    scanf("\n%d", &number);
    while(number!=1000)
    {
        if(number<1||number>1000)
            printf("Input is Invalid\n");
        else
       {
            if(number==1000)
                printf("Goodbye\n");
            if(number<15)
            {
            factorial=number;
            n=number-1;
            while(n>=1)
            {
            factorial=factorial*n;
            n--;

            }
            printf("The Factorial of %d is: %ld\n", number,  factorial);
        }   
        c=a+b;
        printf("Fibonacci Sequence up to %d\n ", number);
        while(c<number&&a+b<number)
            {
                 c=a+b;
                 a=b;
                 b=c;
                 n++;
                 printf("%d\t", c);

                 count=n;
                 if(count%10==0)
                    printf("\n");

            }
            printf("\nTotal:%d\n", n);
            printf("\nPrime numbers up to %d:\n", number);

            while(q<=number)
            {
                prime=0;

                for(r=2;r<q;++r)
                {
                if(q%r==0)
                {
                prime=1;
                }
                }
                if(prime==0)
                {
                printf("%d\t", r);
                w++;
                }
                q++;
                }
                count=r;
                if(count%10==0)
                    printf("\n");
                    printf("\nTotal:%d\n", w);
                }
                printf("\nEnter a Number:\n");
                scanf("\n%d", &number);
                        a=1;
                b=0;                
            }
return(0);
}

最佳答案

您永远不会重置变量 q,它是素数循环的控制变量。最佳做法是创建所有需要在循环内重置的变量。在循环的开头/结尾重置 q,或者在外循环的开头创建 q 并将其设置为 2。

像这样:

while(number != 1000) {
  int q = 2;
  //other assignments below which need to be reset
  ...
  //all other code below
  ... 
}

关于似乎无法找到为什么我的素数程序在重新提示号码后无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425095/

相关文章:

c - 如何遍历C中的Struct数组

c - 如何在没有 math.h 的情况下编写一个简单的对数函数?

c - C 中的管道 - 命令 2 中的错误

c++ - 定义值并通过数组调用它们

c - 虚拟时间已过

c - 为什么我的程序执行完了所有的操作,最后还是崩溃了?

c - 这些 typedef 在 C 中意味着什么?他们在宣布什么?

C tailq队列替换解决性能问题

c - 如何使用 C 从 Windows 获取可用磁盘空间?

c - 为什么 pthread_self 被标记为 attribute(const)?