[英]My c++ program that reads in a matrix and prints out the non-zero numbers is generating a runtime error
這是一個簡單的程序,可從命令行讀取矩陣。 它讀取的前2個數字表示行和列,然后讀取包含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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.