C ++程序打印它应该的另一个主要价值

时间:2014-03-24 04:19:42

标签: c++ primes

这里我有一个C ++程序可以打印2到n个素数。问题是,它打印的数字超过了它需要的数字。例如:n = 20,它打印最多23个而不是19点停止。

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n, status = 1, num = 3, count, c;
    // User input to get n
    cout << "Enter n: ";
    cin >> n;

    // Input is a possible prime number
    if (n >= 1){
        // Print 2 as the first prime number
        cout << 2 << endl;
    }
    // loop that will iterate through n numbers
    for (count = 2 ; count <=n ;){
        // for each element check whether it is prime or not
        for (c = 2 ; c <= (int)sqrt(num) ; c++){
            // Not a prime number if divisble by something other than 1 or itself
            if (num%c == 0){
                status = 0;
                break;
            }
        }
        // Print prime numbers
        if (status != 0){
            cout << num << endl;
            count++;
            // If printed number is greater than n, stop the loop and printing
            if (num >= n){
                status = 0;
                break;
            }
        }
        status = 1;
        num++;
    }         

    return 0;
}

3 个答案:

答案 0 :(得分:1)

问题出在本节:

// Print prime numbers
if (status != 0){
    cout << num << endl;
    count++;
    // If printed number is greater than n, stop the loop and printing
    if (num >= n){
        status = 0;
        break;
    }
}

由于您在打印号码后检查num是否超过了您的结束n,因此您最终会打印一个额外的素数。要解决此问题,您可以简单地重新排列代码,仅在检查条件后进行打印:

// Print prime numbers
if (status != 0){
    // If number is greater than n, stop the loop and printing
    if (num > n){
        status = 0;
        break;
    }

    cout << num << endl;
    count++;
}

请注意我也将num >= n更改为num > n。这将确保如果n是素数,它仍将被打印。 (因此,您指定的范围的最大值将包含在内。)希望这有帮助!如果您有任何问题,请告诉我。

答案 1 :(得分:0)

    // Print prime numbers
    if (status != 0){
        cout << num << endl;
        count++;
        // If printed number is greater than n, stop the loop and printing
        if (num >= n){
            status = 0;
            break;
        }
    }
    status = 1;
    num++;

应该是

    // Print prime numbers
    if (status != 0){
        cout << num << endl;
        count++;
        // If printed number is greater than n, stop the loop and printing
    }
    if (num >= n){
        status = 0;
        break;
    }
    status = 1;
    num++;

答案 2 :(得分:0)

你应该使用&#34; num&#34;不是&#34;伯爵&#34;在循环条件下。

while (num <= n){
        // for each element check whether it is prime or not
        for (c = 2 ; c <= (int)sqrt(num) ; c++){
            // Not a prime number if divisble by something other than 1 or itself
            if (num%c == 0){
                status = 0;
                break;
            }
        }
        // Print prime numbers
        if (status != 0){
            cout << num << endl;
        }
        status = 1;
        num++;
    }