簡體   English   中英

編寫了一個打印素數的程序,但沒有得到所需的輸出。我哪里出錯了?

[英]wrote a program for printing the prime numbers not getting the desired output .where i am going wrong?

無法獲得所需的輸出,幫助找到我的錯誤。我知道我讓它變得復雜,但這是初學者本能思想的實現。 假設如果我給一個輸入值 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;
}

以下代碼:

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;
}

您使用j作為素數變量,所以問題是您在打印之前對j進行了增量操作。 正確的例子是:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM