C++ exercises to create a class Prime, used to determine whether an integer is a prime number



1. Establishing a class Prime, used to determine whether an integer is a prime number. Specific requirements are as follows:

(1) a private data member

int n: an integer store.

(2) public member functions

void set (int _n): the value of the data member is a value of the parameter n of _n.

int IsPrime (): determining whether the data member is a prime number n, is a prime number 1 is returned, otherwise 0.

void print (): if n is a prime number (judged by IsPrime member function), the output "n is a prime number." , and otherwise outputs "n is not a prime number. ".

(3) test the class in the main function.

Defining classes of objects Prime p.

Set the call object member function p, n data member is set to 7 p.

Print member function calls the object p, and outputs the judgment result.

Data member to p n is 9.

Outputs the judgment result.

Correct the output of the Program: .

7 IS A Prime Number. .

9 IS A Not Prime Number.

Sample code:



#include the

 

  

using namespace STD;


class Prime {

Private:

    int n-;

public:

    void set(int _n http://www.cppentry.com  编程开发 程序员入门);

    int IsPrime();

    void print();

};


void Prime::set(int _n)

{

    n = _n;

}


int Prime::IsPrime()

{

    int i;

    for (i = 2; i <= n / 2; i++)

    {

        if (n % i == 0) //%

        {

            return 0;

        }

    }


    return 1;

}


void Prime::print()

{

    int i = IsPrime();

    if (i != 0)

    {

        cout << n << " is a prime number." << endl;

    }

    else

    {

        cout << n << " is not a prime number." << endl;

    }

}


int main()

{

    Prime p;

    p.set(7);

    p.print();


    p.set(`

);

    p.print();


    system("pause");

    return 0;

}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326444194&siteId=291194637