10-200之间的素数只使用while循环C++

Prime numbers from 10-200 using while loops only C++

本文关键字:while 循环 C++ 之间 10-200      更新时间:2023-10-16

大家好,这是我从10-200中查找素数的程序,有人能告诉我怎么了吗?

#include <iostream>
using namespace std;
void main ()
{
    int n=10 , x=2;
    bool t=false;
    while(n<=200)
    {
        while(x<n-1)
        {
            if(n%x!=0)
            {
                x++;
                t=true;
            }
        }
        if(t==true)
        {
            cout<<n <<endl;
            n++;
        }
    }
}

您的代码中有很多错误。我不理解你的逻辑,但你可以这样做:

#include <iostream>
using namespace std;
int main ()
{
    // checking number starting from 10
    int n = 10;
    bool isPrime;
    // as long as the number is less than or equal to 200
    while(n <= 200) {
        // assume the number is prime
        isPrime = true;
        // since prime number is the number that can only be divided by 1 and itself,
        // check if this number can be divided by any number other than 1 or itself
        for (int i = 2; i < n; i++) {
            // if this number can be divided by any number other than 1 or itself,
            if (n%i == 0) {
                // then this is not a prime number, no need to check anymore
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            cout << n << endl;
        }
        // check the next number
        n++;
    }
}