gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:01:36 25 4
gpt4 key购买 nike

这是一个从命令行读取矩阵的简单程序。它读取的前 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/

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