类实现二维数组素数自增

来源:互联网 发布:银行大数据应用 编辑:程序博客网 时间:2024/05/22 05:28
/*建立一个矩阵类 Array,对二维数组中左下三角的全部元素(包括对角线上的元素)作如下变换:(1)若该数不是素数则保持不变;(2)若该数是素数,则用大于它的最小素数替换该数。并统计二维数组中左下三角的全部元素(包括对角线上的元素)中的素数个数。要求如下:(1) 私有数据成员    int x[4][4];存储需要处理二维数组的各元素值。    int count;存储左下三角元素中素数的个数。(2) 公有成员函数    构造函数:进行初始化 x 数组和 count 的值。    int fun(int);判断一个数是否为素数的函数。    int encode( );对 x 数组中左下三角的全部元素(包括对角线上的元素)逐一进行判断,若该数不是素数则保持不变,若该数是素数,则用大于它的最小素数替换该数。    void print():按行输出矩阵的值。(3)编写一个程序测试类,说明(声明)Array 对象 A,将一个矩阵存入对象 A 中,并输出矩阵的值,使用以下测试数据:3   6   4   17      变换后的矩阵为   5   6   4   198   5   9   10                       8   7   9   1012  19  7   20                       12  23  11  204   14  21  23                       4   14  21  29                                             count=6*/#include<iostream>using namespace std;class Array{private:    int x[4][4];    int count;public:    Array(int temp[][4], int);    int fun(int);    int encode();    void print();};Array::Array(int temp[][4], int n = 0){    count = n;    for (int i = 0; i < 4; i++)    {        for (int j = 0; j < 4; j++)        {            x[i][j] = temp[i][j];        }    }}int Array::fun(int n){    for (int i = 2; i < n; i++)    {        if (n%i == 0)            return 0;    }    return 1;}int Array::encode(){    for (int i = 0; i < 4; i++)    {        for (int j = 0; j < 4; j++)        {            if (this->fun(x[i][j]))                count++;            if (this->fun(x[i][j]) == 0)                continue;/* do...while 循环是 while 循环的变体。在检查while()条件是否为真之前,该循环首先会执行一次do{}之内的语句,然后在while()内检查条件是否为真,如果条件为真的话,就会重复do...while这个循环,直至while()为假。*/            do {                x[i][j] += 2;            } while (this->fun(x[i][j]) == 0);        }    }    return 0;}void Array::print(){    for (int i = 0; i < 4; i++)    {        for (int j = 0; j < 4; j++)        {            cout << x[i][j] << '\t';        }        cout << endl;    }    cout << "count=" << count << endl;}int main(){    int a[4][4] = { { 3,6,4,17 },{ 8,5,9,10 },{ 12,19,7,20 },{ 4,14,21,23 } };    Array arr(a);    arr.print();    arr.encode();    arr.print();    system("pause");    return 0;}
原创粉丝点击