通过数组读取矩阵时的奇怪值 [英] Weird values when reading in matrix via array

查看:68
本文介绍了通过数组读取矩阵时的奇怪值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我无法读取/分配矩阵数据(从文件中读取)到我的1-d数组中。假设文件()中的矩阵如下:

Hi all, I have trouble reading/ allocating the matrix data (read from file) into my 1-d array. Suppose the matrix from the file () is as follows:

1 2
3 4





虽然我试图获得其列的总和,而不是获得第0列和第1列的值4,但我的输出显示为32598和1396448268,这是我无法理解的值所有。



这是我目前的代码:



While I am trying to get the sum of its column, instead of getting values 4 for column 0 and 6 for column 1, my output is shown as 32598 and 1396448268, values that I cannot comprehend at all.

This is my current code:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream fin;

    fin.open("/Desktop/matrix.txt");

    int val = 0, rows = 0, cols = 0, numItems = 0;

    // Get the number of rows
    while( fin.peek() != '\n' && fin >> val )
    {
        //cout << "Value in Row is " << val << endl;
        numItems++;
    }
    cols = numItems;

    cout << '\n';

    // Get the number of columns
    while( fin >> val )
    {
        numItems++;
        //cout << "Value in Column is " << val << endl;

        if( numItems%cols == 0 ) 
        {
            cout << '\n';
        }
    }
    rows = numItems/cols;

    // Allocate it as 1-D array
    int arr[rows * cols];

    // read each value into the array
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < cols; j++)
        {
            fin >> arr[i * cols + j];
        }
    }

    int sum = 0;
    for(int j = 0; j < cols; j++)
    {
        for(int i = 0; i < rows; i++)
        {
            sum += arr[i * cols + j];
        }
        cout << "Sum for column " << j << " = " << sum << endl;
    }
}







我在上面某处做错了代码?



我尝试了什么:



但是如果我删除文件读取代码部分并将固定值设置为我的numRows和numCols,输出值将是正确的但不幸的是具有固定值是我不想要的东西,因为我将在不同的文件中读取矩阵的范围可以从2x2 ,3x3,2x4等..



这就是为什么我在文件读取部分实现了获取列数和行数的原因..




Am I doing it wrong somewhere in my above code?

What I have tried:

However if I remove the file-reading code portion and set a fixed value to my numRows and numCols, the output values will be correct but unfortunately having the fixed value is something not I had wanted as I will be reading in different files where the matrix can range from 2x2, 3x3, 2x4 etc..

Which is why I have implemented in the file-reading portion to get the number of columns and rows..

推荐答案

我认为现在是时候停止猜测你的代码在做什么了。是时候看到你的代码正在执行并确保它能达到预期的效果。



调试器是你的朋友。它会告诉你你的代码到底在做什么。

一步一步地执行,检查变量,你会发现它有一个停止做你期望的点。

掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]

http://docs.oracle .com / javase / 7 / docs / technotes / tools / windows / jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html [ ^ ]



I think it is time for you to stop guessing what your code is doing. It is time to see your code executing and ensuring that it does what you expect.

The debugger is your friend. It will show you what your code is really doing.
Follow the execution step by step, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

Quote:

//将其分配为一维数组

int arr [rows * cols] ;

// Allocate it as 1-D array
int arr[rows * cols];

上次检查时,这不是动态分配内存的方法。

Last time I checked, this was not the way to dynamically allocate memory.


您正在从流中读取以检测列和行的数量。完成后,流位置位于文件的末尾。要在之后读取数据,您必须使用 istream :: seekg将流读取位置更改回文件的开头。 - C ++参考 [ ^ ] :

You are reading from the stream to detect the number of colums and rows. Once that is done, the stream position is at the end of the file. To read the data in afterwards you must change the stream read position back to the begin of the file using istream::seekg - C++ Reference[^]:
// Rewind input stream.
// This is missing in your code.
// NOTE: See [EDIT2] below for correct solution.
fin.seekg(0);

// read each value into the array
for(int i = 0; i < rows; i++)
{
    for(int j = 0; j < cols; j++)
    {
        fin >> arr[i * cols + j];
    }
}







还有一个逻辑错误在你的代码中。您想要计算每列的总和,但是您没有清除下一个的 sum 值:




There is also a logical error in your code. You want to calculate the sum for each column but you do not clear the sum value for the next one:

// Move this inside the loop
//int sum = 0;
for(int j = 0; j < cols; j++)
{
    // Move declaration of sum to this position to start with zero for each column
    int sum = 0;
    for(int i = 0; i < rows; i++)
    {
        sum += arr[i * cols + j];
    }
    cout << "Sum for column " << j << " = " << sum << endl;
}



[/ EDIT]





调用 seekg()是不够的。读取完整文件后,将设置failbit并在搜索之前清除它:


[/EDIT]


Calling seekg() is not enough. When the complete file has been read, the failbit is set and must be cleared before seeking:

// Rewind input stream.
// This is missing in your code.
fin.clear();
fin.seekg(0);





这篇关于通过数组读取矩阵时的奇怪值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆