注册 登录
编程论坛 C++教室

一个根据经定的阶数产生单位矩阵的问题

afraidhlq 发布于 2008-03-18 21:35, 924 次点击
下面是代吗,能通过编译无错误,但N>6时不能程序出错
谢谢大侠们,告诉我要怎么才能改进
我的程序缺陷在哪里?
class Lx1
{
public:
    input();
    chushi();
    diplay();
private:
    int n;
    int i;
    int jz[];
};
//////////////////////////
#include<iostream.h>
#include "Lx1.h"
Lx1::input()
{
    cout << "\n input n:" <<endl;
    cin >> n;
}
Lx1::diplay()
{
    for(i=0;i<n*n;i++)
        cout << jz[i] ;
}
Lx1::chushi()
{
    int j,k;
    j=n*n;
    k=n+1;
    for(i=0;i<j;i++)
        jz[i]=0;
    for(i=0;i<j;i=i+k)
        jz[i]=1;
}
/////////////////////////
#include "Lx1.h"
void main()
{
    Lx1 a;
    int x=1;
    while(x=1)
    {
    a.input();
    a.chushi();
    a.diplay();
    }

}
2 回复
#2
VanHorn2008-03-19 09:54
楼主不打算用new和delete吗?如果是我来做这个题目,我会这样:
#include<iostream.h>

class Lx1
{
public:
    Lx1();
    ~Lx1();
    input();
    chushi();
    diplay();
private:
    int n;
    int i;
    int j;
    int **jz;
};
//////////////////////////


Lx1::Lx1()
{
    jz=NULL;
}

Lx1::~Lx1()
{
    delete jz;
}

Lx1::input()
{
    cout << "\n input n:" <<endl;
    cin >> n;
    jz=new int*[n];
    for(i=0;i<n;i++)
    {
        jz[i] = new int[n];
    }

}
Lx1::diplay()
{
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            cout << jz[i][j] ;

        }
        cout<<endl;
    }
        
}
Lx1::chushi()
{
  
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            if(i==j)
            {
                jz[i][j]=1 ;

            }
            else
            {
                jz[i][j]=0 ;

            }
        

        }
    }
}
/////////////////////////

void main()
{
    Lx1 a;
    int x=1;
    while(x==1)
    {
    a.input();
    a.chushi();
    a.diplay();
    cout<<"继续请按1,退出请按其他键。"<<endl;
    cin>>x;
    }

}


呵呵,我也常常用计算机做数学题啊。所以看到这个楼主这个问题很有同感。希望以后多交流。对你的代码改动比较大,不过我觉得用一个二维指针比较直接。我的代码放在一个.cpp中直接编译就可以运行了。以前也看到有朋友专门为此写了一个二维指针类。
#3
afraidhlq2008-03-19 12:56
谢谢你啊,我是才开始学C++,这些东西还没学到呢,真的很感谢!
可是,我那种方法为什么对大于6的n就出错呢,迷茫
1