注意:我有两个同名的变量......非常感谢Stefan Birladeanu和Henrik注意到这一点!*
最近我开始编写代码,帮助我输入bool函数的值到Veitch(Karnaugh)图中的4个变量。代码应该将元素写入矩阵大小4x4,但使用这些索引:
元素 - 索引1,1 这是main()的代码:
void main()
{
int n;
n=4;
int **VeitchDiagram;
//allocate memory for Veitch diagram
VeitchDiagram = new int *[n];
for(int i=0; i<n; i++)
VeitchDiagram[i]=new int [n];
//enter the elements
for(int i=0; i<n; i++)
{
int j, k;
if(i%2==1)
{
k=0;
if(i<2)
j=4;
else
j=-1;
for(int k=0; k<2; k++)
{
if(i<2)
j--;
else
j++;
cin >> VeitchDiagram[k][j]; //this part writes the input to elements with index (at least it should do that):
k++; //0,3 1,3 0,2 1,2 if i%2==1 and i<2
cin >> VeitchDiagram[k][j]; //0,0 1,0 0,1 1,1 if i%2==1 and i>=2
k--;
}
}
else
{
k=3;
if(i<2)
j=4;
else
j=-1;
for(int k=0; k<2; k++)
{
if(i<2)
j--;
else
j++;
cin >> VeitchDiagram[k][j]; //this part writes the input to elements with index (at least it should do that):
k--; //3,3 2,3 3,2 2,2 if i%2==0 and i<2
cin >> VeitchDiagram[k][j]; //3,0 2,0 3,1 2,1 if i%2==0 and i>=2
k++;
}
}
}
//free memory allocated for VeitchDiagram
for(int i=0; i<n; i++)
delete [] VeitchDiagram[i];
delete [] VeitchDiagram;
}
答案 0 :(得分:2)
for(int k=0; k<2; k++)
{
if(i<2)
j--;
else
j++;
cin >> VeitchDiagram[k][j]; //this part writes the input to elements with index (at least it should do that):
k--; //3,3 2,3 3,2 2,2 if i%2==0 and i<2
cin >> VeitchDiagram[k][j]; //3,0 2,0 3,1 2,1 if i%2==0 and i>=2
^ k == -1
但你真的应该学习如何使用调试器。
答案 1 :(得分:2)
对于i = 0,你到达这个分支
else
{
k=3;
if(i<2)
j=4;
else
j=-1;
for(int k=0; k<2; k++)
{
if(i<2)
j--;
else
j++;
cin >> VeitchDiagram[k][j]; //this part writes the input to elements with index (at least it should do that):
k--; //3,3 2,3 3,2 2,2 if i%2==0 and i<2
cin >> VeitchDiagram[k][j]; //3,0 2,0 3,1 2,1 if i%2==0 and i>=2
k++;
}
}
当k = 0时
cin >> VeitchDiagram[k /* = 0 OK */][j]; //this part writes the input to elements with index (at least it should do that):
k--; //decrease it //3,3 2,3 3,2 2,2 if i%2==0 and i<2
cin >> VeitchDiagram[k /* here k = -1 BAD!!! */][j]; //3,0 2,0 3,1 2,1 if i%2==0 and i>=2
k++;
答案 2 :(得分:1)
如其他地方所述,您要在数组外部建立索引。
const size_t k_index[] = {3,2,3,2,0,1,0,1,3,2,3,2,0,1,0,1};
const size_t j_index[] = {3,3,2,2,3,3,2,2,0,0,1,1,0,0,1,1};
int main()
{
const int n = 4;
int VeitchDiagram[n][n]; // No need for dynamic allocation here.
//enter the elements
for(int i = 0; i < n * n; i++)
{
cin >> VeitchDiagram[k_index[i]][j_index[i]];
}
}
它也有几行。