我的程序中的素数部分有问题。当我编译并运行我的程序时,素数打印出第一个数字正常,但是当重新计算另一个数字时。它通常打印出没有数字或者从某个点向下切断素数。我是编码和这个论坛的新手,所以我很抱歉我的帖子中有任何格式问题。
#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);
}
答案 0 :(得分:2)
您永远不会重置变量q,它是素数循环的控制变量。最佳做法是创建需要在循环内重置的所有变量。在循环的开头/结尾重置q,或在外循环的开头创建q并将其设置为2.
像这样:
while(number != 1000) {
int q = 2;
//other assignments below which need to be reset
...
//all other code below
...
}