我的c++程序读取一个矩阵并打印出非零的数字,这产生了一个运行时错误
My c++ program that reads in a matrix and prints out the non-zero numbers is generating a runtime error
这是一个从命令行读取矩阵的简单程序。它读入的前两个数字代表行和列,然后读入一个包含0的浮点数矩阵。它逐行读取这些数据,并将该行临时存储在浮点数数组中。当它读入该行时,它检查非零数字并增加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++中程序的名称。
这样做效果更好,主要的变化是修改了ar和ac的初始化,以及内循环的第一行。
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, const 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
arr[j] = atoi(argv[(ar * i) + j + 3]);
//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;
}
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 以C++输出一个数字三角形
- 反转一个数字程序不起作用,为什么?
- 如何让用户在 c++ 中选择一个数字
- 输出一个数字,该数字可能是三种类型之一
- C++在不使用pow或循环的情况下计算一个数字的幂
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 找到所有与自己求和的数字X的快速方法,去掉一个数字得到N
- C++[递归]将一个数字写成2的升序之和
- 试图找到一个数字的平方根,但代码不起作用。C++
- 我没有得到一个数字作为输出,而是一个表情符号
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 你怎么编码,如果x不等于一个数字,程序就会退出
- 如何将整数数组相乘得到一个数字?
- 为无符号字符* 分配一个数字
- 如何以更有效的方式检查一个数字是否是素数?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 字符串和双精度的麻烦,等值后再得到一个数字