簡體   English   中英

C程序-質數

[英]C Program - Prime numbers

確定數字是否為質數。 使用代碼塊13.12執行。 編譯器GNU GCC 4.7.0

#include <stdio.h>

main()
{
    int input,check,count;

    printf("Enter the number: ");
    scanf("&d",&check);

    count=0;        
    for(check=1;check<=1;check++)
    {
        if((input%check)==0)
        {
            count++;
        }
    }
    if(count==2)
    {
        printf("The number %d is prime",check);
    }
    else
    {
        printf("The number %d is not prime",check);
    }
}

請注意,沒有錯誤或警告。 但是即使在給出其他輸入后,編譯器仍假定數字為“ 2”,並且說2不是質數!

scanf("&d",&check);

應該

//     v-- percent, not ampersand
scanf("%d",&check);

或(可能)

scanf("%d", &input);

...因為讀入input變量會更有意義。 然后,在程序的后面,

printf("The number %d is prime", check); 

應該

printf("The number %d is prime\n", input);

因為您正在檢查input ,而不是check 下面的兩行相同。 最后,循環條件

for(check=1;check<=1;check++)

沒有意義。 該循環將只運行一次,並且您不想測試輸入是否可以被1整除。

                 // v-- check factors until input
for(check=1;check<=input;check++)

這不是這里最有效的檢查,但是它可以幫助您入門。

旁注:原型

main()

僅與C89兼容。 從C99開始,不再包含舊的K&R函數聲明方法,並且main的適當等效原型為

int main(void)

因此,當您修復問題時,應將其放在那里。

一些問題是:

  1. 未定義包含垃圾值的變量input
  2. for(check=1;check<=1;check++)這似乎不正確,在所有情況下僅循環一次。
  3. 通過將格式說明符傳遞為%d而不是&d來使用scanf讀取值。

好吧,我認為總歸結為有人為問詢者編寫代碼。

#include <stdio.h>
#include <conio.h>

int main() // note "int" before "main()"
{
    int input, check, count;
    printf("Enter the number: ");
    scanf("%d", &input); //I believe this is what you meant instead of storing the inputted value in "check"

    count = 0;
    check = 2; //Check should equal "2" because anything divided by one will have no remainder


    while((count != 1) && (check <= 50)) //If you want to stop trying to divide when the number you're dividing by is above 50, change this line. I stopped at 50 just as a random number, but I'm sure there's a more logical one to use. ------ "while(count != 1)" stops the loop when the number is successfully divided.

    {
        if (check == input) break; // stop checking when the number we're trying to divide is equal to the number to divide by.

        if((input%check) == 0)
        {
            count++;
        }

        check++; //increment the number we're checking by
    }

    if(count == 1)
    {
        printf("The number %d is not prime\n", input); // output the number the user tried to input
    }

    else
    {
        printf("The number %d is prime\n", input);
    }

    getch();
    return 1;
}

我懇求您閱讀並理解它們,而不是僅僅復制代碼,因為我已經看過很多次了。

編輯:我最初包含c ++函數的錯誤。 現在在C中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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