Can';我似乎不明白为什么我的素数程序没有';重新输入数字后不能正常工作
我在程序的素数部分遇到了问题。当我编译并运行我的程序时,第一个数字的素数打印出来的很好,但是当另一个数字被重新打印出来时。它通常不打印任何数字,或者从某一点向下截断素数。我是新的编码和这个论坛,所以我很抱歉在我的文章中有任何格式问题Can';我似乎不明白为什么我的素数程序没有';重新输入数字后不能正常工作,c,C,我在程序的素数部分遇到了问题。当我编译并运行我的程序时,第一个数字的素数打印出来的很好,但是当另一个数字被重新打印出来时。它通常不打印任何数字,或者从某一点向下截断素数。我是新的编码和这个论坛,所以我很抱歉在我的文章中有任何格式问题 #include <stdio.h> #include <math.h> int main(void) { int number, n=1; long factorial=1; int a=1, b=0,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);
}
#包括
#包括
内部主(空)
{
整数,n=1;
长阶乘=1;
int a=1,b=0,c;
int q=2,r=2,w=0;
整数素数,计数;
printf(“输入一个数字:\n”);
scanf(“\n%d”,编号(&n));
while(数字=1000)
{
如果(数字1000)
printf(“输入无效\n”);
其他的
{
如果(数字=1000)
printf(“再见”);
如果(数字=1)
{
阶乘=阶乘*n;
n--;
}
printf(“%d的阶乘是:%ld\n”,数字,阶乘);
}
c=a+b;
printf(“高达%d\n的斐波那契序列”,编号);
而(c您永远不会重置变量q,它是素数循环的控制变量。最佳做法是创建所有需要在循环内重置的变量。在循环的开始/结束处重置q,或者在外循环的开始处创建q,并将其设置为2
像这样:
while(number != 1000) {
int q = 2;
//other assignments below which need to be reset
...
//all other code below
...
}
请正确缩进代码,最后一个数字提示似乎在qscanf(“\n%d”,&number);->中,这不是很邪恶吗?没有使用math.h
中的任何内容!包含未使用的头文件是一种糟糕的编程实践。为了便于阅读和理解:1)单独的代码块(for,if,else,while,do…while,switch,case,default)通过一个空行。2)遵循公理:每行只有一条语句,每一条语句(最多)一个变量声明。3)一致地缩进代码。在大括号“{”中每次打开后缩进。在每个关闭大括号“}之前取消缩进“。建议每个缩进级别为4个空格。适当的水平间距,例如在括号内、逗号后、分号后。环绕运算符使代码更易于阅读。谢谢,这是有意义的!知道为什么我的计数变量在10处截断每行打印的数字不起作用吗?它适用于具有相同的格式。我猜我缺少了一些关于r的东西,因为我为素数设置了count=r?@ryanContols它可能与这样一个事实有关:检查count变量是否可被10整除的if语句不在计算素数的while循环中。上面的格式很难看出。我刚刚意识到y斐波那契序列在重发后也不起作用,是因为同样的原因素数不起作用吗?啊,没关系,我忘了在最后重新初始化a和b值,谢谢你的帮助help@ryancontois没问题。如果您认为答案解决了您的问题,请单击复选标记接受它。这将有助于保持重点n个未回答的问题。