gpt4 book ai didi

c++ - 二维数组未显示正确的输出

转载 作者:行者123 更新时间:2023-11-28 08:05:41 24 4
gpt4 key购买 nike

我希望用户在二维数组中输入值。他还可以选择每个维度的大小

    int main()
{
int x;
int y;
int *p;
cout<<"How many items do you want to allocate in dimension x?"<<endl;
cin>>x;
cout<<"How many items do you want to allocate in dimension y?"<<endl;
cin>>y;
p = new int[x,y];
for(int i=0; i<x; i++) //This loops on the rows.
{
for(int j=0; j<y; j++) //This loops on the columns
{
int value;
cout<<"Enter value: "<<endl;
cin>>value;
p[i,j] = value;
}
}
drill1_4 obj;
obj.CopyArray(p,x,y);

}

然后,通过

输出二维数组
class drill1_4
{
public:
void CopyArray(int*,int,int);
private:
int *p;
};

void drill1_4::CopyArray(int* a,int x,int y)
{
p = a;
for(int i=0; i<x; i++) //This loops on the rows.
{
for(int j=0; j<y; j++) //This loops on the columns
{
cout << p[i,j] << " ";
}
cout << endl;
}
getch();
}

逻辑看起来不错,但是假设,如果用户输入数字,数组应该如下所示

1 2

3 4

但是,它看起来像这样:

3 3

4 4

数组显示不正确。

最佳答案

不知道您是否找到了问题的答案。上面的评论告诉你哪里错了。这是一个可能的答案。

#include <cstdio>

#include <iostream>
using namespace std;

class drill1_4
{
public:
void CopyArray(int**,int,int);
private:
int **p;
};

void drill1_4::CopyArray(int** a,int x,int y)
{
p = a;
for(int j=0; j<y; ++j) //This loops on the rows.
{
for(int i=0; i<x; ++i) //This loops on the columns
{
cout << p[i][j] << " ";
}
cout << endl;
}
cin.get();
}


int main()
{
int x;
int y;
int **p;
cout<<"How many items do you want to allocate in dimension x?"<<endl;
cin>>x;
cout<<"How many items do you want to allocate in dimension y?"<<endl;
cin>>y;
p = new int*[x];
for (size_t i = 0; i < x; ++i)
p[i] = new int[y];

for(int j=0; j<y; ++j) //This loops on the rows.
{
for(int i=0; i<x; ++i) //This loops on the columns
{
int value;
cout<<"Enter value: "<<endl;
cin>>value;
p[i][j] = value;
}
}
drill1_4 obj;
obj.CopyArray(p,x,y);
}

我不确定我是否理解 x 维度的含义。如果你的意思是 x 水平运行,那么我认为 i 和 j for 循环应该颠倒过来,因为 x 将代表列。

关于c++ - 二维数组未显示正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10335685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com