[英]Index was outside the bounds of array
當我嘗試運行應用時,它顯示Index was outside the bounds of the array
在float[] u_f = a[userid];
行Index was outside the bounds of the array
float[] u_f = a[userid];
任何想法? PS。 用戶ID可以是每個整數,但我采用的整數索引介於(0,1143600表示項目)和(0,89395表示用戶)之間,我的計算基於此。然后,我的計算基於的索引userid
值存儲在陣列中的不基於所述值userid
。 提前致謝
float[][] a = Enumerable.Range(0, 89395).Select(i => new float[100]).ToArray();
float[][] b = Enumerable.Range(0, 1143600).Select(j => new float[100]).ToArray();
int[] c = new int[1258038];
int[] d = new int [92160];
........
public float dotproduct(int userid, int itemid)
{
result = 0f;
float[] u_f = a[userid]; // <----Error Line (index was outside the bounds of array)
float[] i_f = b[itemid];
for (int i = 0; i < u_f.Length; i++)
{
result += u_f[i] * i_f[i];
}
return result;
}
private void btn_recomm_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtbx_id.Text) && String.IsNullOrEmpty(txtbx_itemid.Text) && !String.IsNullOrEmpty(txtbx_noofrecomm.Text))
{
int sc = Convert.ToInt32(txtbx_id.Text);
int n = Convert.ToInt32(txtbx_noofrecomm.Text);
int userseq=Array.IndexOf(d, sc);
var results = new List<float>(1143600);
for (int z = 0; z <= 1143600; z++)
{
results.Add(dotproduct(userseq, z));
}
var sb1 = new StringBuilder();
foreach (var resultwithindex in results.Select((r, index) => new { result = r, Index = index }).OrderByDescending(r => r.result).Take(n))
{
sb1.AppendFormat("{0}: {1}", d[resultwithindex.Index], resultwithindex.result);
sb1.AppendLine();
}
MessageBox.Show(sb1.ToString());
}
if (!String.IsNullOrEmpty(txtbx_id.Text) && !String.IsNullOrEmpty(txtbx_itemid.Text) && String.IsNullOrEmpty(txtbx_noofrecomm.Text))
{
int uid = Convert.ToInt32(txtbx_id.Text);
int iid = Convert.ToInt32(txtbx_itemid.Text);
int userseq0 = Array.IndexOf(d, uid);
int itemseq0 = Array.IndexOf(c, iid);
dotproduct(userseq0, itemseq0);
MessageBox.Show("The Score of item id " + itemseq0 + " is " + result);
}
顯然,以userid
值等於或大於a.Length
調用dotproduct
。
如果不應該發生這種情況,請在聲明u_f
數組之前添加以下行:
Debug.Assert(a.Length > userid);
當然,這本身並不能解決問題,但可以確保您在進行測試時,無論何時發生這種情況,都不會被忽視或吞咽。
附帶說明一下,更清晰的變量名將使您更容易閱讀代碼並找出問題。 如果可能的話,使用實際類型而不是鋸齒狀的數組也可能會有所幫助。
這意味着userID
的值高於數組a
的最大索引號。 最大索引為count-1。
錯誤消息中提到了這一點。
此外,它看起來像a
是二維的。 這可能是您的問題嗎?
用[userid]替換
a[userid-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.