如何修复“索引超出数组的范围”错误

时间:2014-02-19 14:38:06

标签: c#

我在第c[x,y]+=linei*lineu;行中找到了“索引超出数组范围”错误。结果矩阵的大小必须是[1,1143600]。 我必须从第二个文件读取一行第一个文件和1143600行(矩阵形状,它们必须是列)(每个行在两个数据集中都有100个浮点数)并且它们必须相乘(比如乘以两个矩阵)。

另外,如何使用skip方法执行以下代码。

for (int counter = 0; counter <= i; counter++)
   {
      USER.ReadLine();
   }

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace DEMO_3
{
    public partial class Form1 : Form
    {
        float[,] c = new float[1, 1143600];
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_recomm_Click(object sender, EventArgs e)
        {
              //get the user input from text box
            int sc = Convert.ToInt32(txtbx_sc.Text);
            int i=sc*100;
            //read both dataset
            StreamReader USER = new StreamReader("c:\\1.txt");
            StreamReader ITEM = new StreamReader("c:\\2.txt");
              for (int counter = 0; counter <= i; counter++)
                {
                  USER.ReadLine();
                }

                for (int x = 0; x < 1143600; x++)
                   {
                      for (int y = 0; y < 100; y++)
                        {
                          float lineu=Convert.ToSingle(USER.ReadLine());
                          float linei=Convert.ToSingle(ITEM.ReadLine());
                          c[x,y]+=linei*lineu;

                    }
                }
                var allValues = c.OfType<float>();
                using (var filestream = new FileStream("DEMO.txt", FileMode.Create))
                using (var streamwriter = new StreamWriter(filestream))
                {
                    foreach (double valuec in allValues)
                        streamwriter.WriteLine(valuec);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

试试这个: 暗中你的矩阵:

float[,] c = new float[1143600, 100];

并更改此循环代码:

for (int y = 0; y < 100; y++)
{
    for (int x = 0; x < 1143600; x++)
    {
        float lineu=Convert.ToSingle(USER.ReadLine());
        float linei=Convert.ToSingle(ITEM.ReadLine());
        c[y,x]+=linei*lineu;
    }
}