[英]wrote a program for printing the prime numbers not getting the desired output .where i am going wrong?
not able to get the desired output,help to find my error.I know that I made it complex,but this is implementation of instinct thought from beginner.无法获得所需的输出,帮助找到我的错误。我知道我让它变得复杂,但这是初学者本能思想的实现。 For suppose if I give a input value 5 the output value showing is 3,4,6,8,12 where actual output should be 2,3,5,7,11.
假设如果我给一个输入值 5,输出值显示为 3、4、6、8、12,其中实际输出应为 2、3、5、7、11。
#include <stdio.h>
#include<conio.h>
int main()
{
int count,n,counte=0,j=2,i;
printf("enter a number of prime numbers to print:");
scanf("%d",&n);
for(counte=1;counte<=n;)//for no.of prime numbers to be printed
{
while(j<=(j+1))
{
count=0;
for(i=1;i<=j;i++)
{
if((j%i)==0)
{
count++;
}
}
if(count==2)
{
printf("%d \n",j);
counte++;
j++;
break;
}
j++;
}
}
getch();
return 0;
}
the following code:以下代码:
compiles cleanly
performs the desired operation
checks for errors
is consistently indented
#include <stdio.h>
//#include<conio.h>
#include <stdlib.h>
int main()
{
int count;
int n;
int counte=0;
int j=2; // number to test to see if it is prime
int i;
printf("enter a number of prime numbers to print:");
if( 1 != scanf("%d",&n) )
{ // then scanf failed
perror( "scanf failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
if( 0 > n )
{
printf( "positive counts only\n");
exit( EXIT_FAILURE );
}
// implied else, num primes to print is positive
for(counte=0, j=2; counte<n; j++)//for no.of prime numbers to be printed
{
count=0;
for(i=1;i<=j;i++)
{
if((j%i)==0)
{
count++;
}
}
if(2 == count)
{
printf("%d \n",j);
counte++;
}
} // end for
getchar(); // gets leftover newline
getchar(); // waits for user to hit a key
return 0;
}
You are using j
as the prime number variable, so the problem is that your are making an incremental operation for j
before printing.您使用
j
作为素数变量,所以问题是您在打印之前对j
进行了增量操作。 The correct example would be:正确的例子是:
#include <stdio.h>
#include<conio.h>
int main()
{
int count,n,counte=0,j=2,i;
printf("enter a number of prime numbers to print:");
scanf("%d",&n);
for(counte=1;counte<=n;)//for no.of prime numbers to be printed
{
while(j<=(j+1))
{
count=0;
for(i=1;i<=j;i++)
{
if((j%i)==0)
{
count++;
}
}
// Here was incremental.
if(count==2)
{
printf("%d \n",j);
counte++;
break;
}
j++; //Here is now.
}
}
getch();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.