c++ - 使用二维数组创建矩阵

标签 c++ arrays matrix

我一直在编写一个程序,对两个方阵进行一些操作。目前,我一直在考虑编写一个代码来读取固定(先前已知大小)的矩阵,并将这些数据写入二维数组。但是,我遇到了一个问题,因为当我使用令人上瘾的输出消息调试代码时,一切似乎都很好,但最终的输出( for 循环中的输出)我缺少一些数字。这真的很奇怪,因为当我打印过程中使用的所有变量时,它们的值看起来很好。

#include <iostream>
#include <stdio.h>

using namespace std;

int main () 
{
    int number = 0; 
    int index = 0;
    int v_ind = 0;  // vertical index
    int h_ind = 0;  // horizontal index
    char c;
    int size = 3;   // temporary fixed size
    int searched_number;
    int matrix1 [size-1][size-1];
    int matrix2 [size-1][size-1];

    //scanf("%i %i", &size, &searched_number);


    while (index < size)
    {
        c = getchar_unlocked();

        if ( (c >= '0') && (c <= '9') )
        {
            number = (number * 10) + (c - '0');
            continue;
        }

        if (c == ' ')
        {   
            cout << "number on a space: " << number << endl;
            matrix1[h_ind][v_ind] = number;
            cout << "1 ) matrix1[" << h_ind << "][" << v_ind << "] : " <<  matrix1[h_ind][v_ind]  << endl << endl;
            v_ind ++ ;
            number = 0;
            continue;
        }

        if (c == '\n')
        {   
            cout << "num on a newLine: " << number << endl;
            matrix1[h_ind][v_ind] = number;
            cout << "2) matrix1[" << h_ind << "][" << v_ind << "] : " << matrix1[h_ind][v_ind] << endl << endl;
            h_ind ++ ;
            v_ind = 0;
            number = 0;
            index ++ ;
            continue;
        }

    }



    for (int i = 0; i < size; i ++) {
        for (int j = 0; j < size; j ++) {
            int num = matrix1[i][j];
            cout << "mat[" <<i <<"][" << j << "] : " << num << " " << endl;
        }
    }
}

下面我粘贴了来自 Ideone.com 的矩阵示例输出,如下所示:
| 1 2 3 | 1 2 3
| 4 5 6 |
| 7 8 9 | 7 8 9

Sukces   time: 0 memory: 3348 signal:0
number on space: 1
1 ) matrix1[0][0] : 1

number on space: 2
1 ) matrix1[0][1] : 2

num na newLine: 3
2) matrix1[0][2] : 3

number on space: 4
1 ) matrix1[1][0] : 4

number on space: 5
1 ) matrix1[1][1] : 5

num na newLine: 6
2) matrix1[1][2] : 6

number on space: 7
1 ) matrix1[2][0] : 7

number on space: 8
1 ) matrix1[2][1] : 8

num na newLine: 9
2) matrix1[2][2] : 9

mat[0][0] : 1 
mat[0][1] : 2 
mat[0][2] : 4 
mat[1][0] : 4 
mat[1][1] : 5 
mat[1][2] : 7 
mat[2][0] : 7 
mat[2][1] : 8 
mat[2][2] : 9 

问题看起来很简单 - 我丢失了每一行的所有最后一个数字,除了最后一个数字。我怀疑我在某个地方覆盖了正确的值,但我不知道在哪里。

最佳答案

您将矩阵创建为matrix1[size-1][size-1],其索引从0到size-2。然后您尝试打印从索引 o 到 size-1 的值。尝试将矩阵声明为

int matrix1 [size][size]

关于c++ - 使用二维数组创建矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419131/

相关文章:

c++ - 如何通过多个键索引和查询 STL 映射容器?

c++ - 即使边界键不存在,我也可以迭代 std::map 键范围吗?

java - 使用 HTTP Get 发送数组

arrays - Bash函数在多行上打印数组

c++ - 将 RotateAxisAngle 反转回角度

c++ - 我们如何在销毁时捕获标准类?

c++ - 用 wxWidgets 绘图

ruby - 新行列表到数组中

交换对称矩阵中两个索引的算法

c++ - C++ 中的矩阵类 : An Explanation