2015-11-11 34 views
1

我試圖讓反對時刻電荷之間的圖表,我得到這個錯誤:指數在圖形數組的範圍之外繪製C#

Index was outside the bounds of array

我的代碼如下:

namespace WindowsFormsApplication19 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      double max = 24000000, min = 23999999.85; 
      double[] q = new double[9]; 
      int t = 0; 
      for (t = 1; t <= 10; t++) 
      { 
       q[t] = (24 * Math.Pow(10, 6)) * Math.Exp(-t/(2000 * Math.Pow(10, 6))); 
       chart1.Series[0].Points.AddXY(t, q[t]); 
      } 

      chart1.ChartAreas[0].AxisY.Maximum = max; 
      chart1.ChartAreas[0].AxisY.Minimum = min; 
      chart1.Series[0].ChartType = SeriesChartType.FastLine; 
      chart1.Series[0].Color = Color.Red; 
     } 
    } 
} 

我試過,但我仍然有同樣的問題:

private void button1_Click(object sender, EventArgs e) { 

    double[] q = new double[9]; 
    int t = 0; 
    for (int i = 0; i <= 9; i++) 
    { 
     for (t = 1; t <= 10; i++) 
     { 
      q[i] = (24 * Math.Pow(10, 6)) * Math.Exp(-t/(2000 * Math.Pow(10, 6))); 
      chart1.Series[0].Points.AddXY(t, q[i]); 
     } 
    } 

} 
+1

陣列索引0爲主。從0開始到8.注意'q'長度9.所以,你應該從0到8不爲1〜10 –

回答

0

索引越界意味着你的代碼試圖寫入高於最高索引的索引。

你在你的代碼2個問題,導致這個 - 你需要同時修改前,將正常工作。

1.修正q

在你的代碼有它有9個指標,從08數組q,但它看起來像你想10:new double[10]

2.修正循環

在爲你看你的循環,從1到10,但陣列啓動索引爲0(你有10個指標,從0〜9)。您需要t以0開始,而不是1

namespace WindowsFormsApplication19 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      double max = 24000000, min = 23999999.85; 
      double[] q = new double[10]; // Fix q: length of 10 
      for (int i = 0; i < q.Length; i++) // Fix loop: start at 0 
      { 
       int t = i + 1; // Fix loop: t and i need to have different values 
       q[i] = (24 * Math.Pow(10, 6)) * Math.Exp(-t/(2000 * Math.Pow(10, 6))); 
       chart1.Series[0].Points.AddXY(t, q[i]); 
      } 

      chart1.ChartAreas[0].AxisY.Maximum = max; 
      chart1.ChartAreas[0].AxisY.Minimum = min; 
      chart1.Series[0].ChartType = SeriesChartType.FastLine; 
      chart1.Series[0].Color = Color.Red; 
     } 
    } 
} 
+0

感謝開始,但仍具有「索引數組的範圍外」的錯誤在t = 10 曲線圖僅示出從t = 1到9 但在t = 10它是否顯示錯誤 –

+0

值你忘記改變'q [噸]''到q [I]'中的一個?或者't'應該從0開始? –

+0

不,我已經改變了所有q [t]到q [i],並且t不應該從0開始,它應該從1開始到10 –

0

你的數組可以包含10個元素,因爲:

double[] q = new double[9];

您的迴路達到10時;這意味着你想要達到q [10],這將導致索引超出數組錯誤的範圍。

你不應該增加你的循環指數超過9

1

在for循環它是更標準去從0到< q.Length。

這樣,你可以改變你的數組的長度和for循環仍然可以工作。

 double[] q = new double[9]; 
     for (int t = 0; t < q.Length; t++) 
     { 
      q[t] = (24 * Math.Pow(10, 6)) * Math.Exp(-t/(2000 * Math.Pow(10, 6))); 
      chart1.Series[0].Points.AddXY(t, q[t]);    
     }