c++ - 我的读入矩阵并打印出非零数字的 C++ 程序正在生成运行时错误

标签 c++ matrix

这是一个从命令行读取矩阵的简单程序。它读取的前 2 个数字代表行和列,然后读取包含 0 的 float 矩阵。它逐行读取这些并将该行临时存储在一个 float 组中。当它读入该行时,它会检查非零数字并递增 nz,nz 存储每行的非零数字的数量,nztotal 是非零数字的总数。然后它通过这个数组返回并打印出每个非零数字的索引和值。它必须返回数组,以便它可以先打印出 nz。这是代码:

     #include <iostream>
        #include <stdlib.h>
        using namespace std;

        int main(int argc, char* argv[]) {
            //puting the rows and columns into ints
            int ar = atoi(argv[1]);
            int ac = atoi(argv[2]);
            //printing out the rows;
            cout<< ar;
            int nz = 0;
            int nztotal = 0;
            //creating an array of floats
            float* arr = new float[ac];
            //reading through line by line
            for(int i = 0; i < ar;i++)
            {
                cout << endl;
                nz = 0;
                //reading through number by number
                for(int j = 0;j < ac; j++)
                {
                    //storing each number in the array
                    cin>> arr[j];
                    //checking if the number is non-zero and incrementing nz and nztotal
                    if(arr[j] != 0)
                    {
                        nz++;
                        nztotal++;
                    }
                }
                //printing out nz
                cout<< nz;
                //reading through the array and printing out the values and index of each non-zero number
                for(int j = 0;j < ac; j++)
                {
                    if(arr[j] != 0)
                    {
                        int temp = j + 1;
                        cout<< temp << arr[j];
                    }
                }
            }
            cout<< nztotal;
        }

这是一个示例输入:

4 4 2 0 3 0 2 0 3 0 2 0 3 0 2 0 3 0

这应该产生这样的输出:

4
2 1 2 3 3
2 1 2 3 3
2 1 2 3 3
2 1 2 3 3
8

但是它却生成了一个运行时错误,并且没有任何内容被打印出来。我很确定这只是我在做一些愚蠢的事情

最佳答案

你检查过argc了吗? argv[0] 是 C++ 程序的名称。参见 this post了解一些细节。

关于c++ - 我的读入矩阵并打印出非零数字的 C++ 程序正在生成运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33179729/

相关文章:

c++ - 在 GDI 中获取像素

C++ 模板参数之间的比较似乎被忽略了

c++ - 了解 std::transform 以及如何打败它

c++ - 使用 OpenCV 保存 DFT 的频谱

python - 遍历列表和数组

Python构建numpy矩阵

c++ - 在 C++ 中使用 vector 从文本文件中读取矩阵

c++ - 避免在继承的树类中向下转型

使用 R 中的坐标从矩阵中删除值

r - 根据另一个矩阵改进矩阵操作的 for 循环的方法