我正在嘗試編寫一個c#代碼,用於獲取鋸齒陣列的學生成績(每個學生的成績數量可以不同)並計算每個學生的平均成績。這裏是我的代碼:如何將一個數組添加到整數c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace students_avg
{
class Program
{
static void Main(string[] args)
{
int n,m,i,j,count=0,avg;
Console.WriteLine("please enter the number of students");
n = Convert.ToInt32(Console.ReadLine());
int [][] student = new int [n+1][];
for (i = 1; i <= n; i++)
{
Console.WriteLine("how many grades does student number " + i + "have?");
m = Convert.ToInt32(Console.ReadLine());
student[i] = new int[m];
Console.WriteLine("please enter student number " + i + "'s grades");
for (j = 1; j <= m; j++)
{
student[i] =new int[] {Convert.ToInt32(Console.ReadLine())};
count +=Convert.ToInt32(student[i]);
}
avg = count/m ;
Console.WriteLine("the student number " + i + "'s average is " + avg);
}
Console.ReadKey();
}
}
}
但我有問題,因爲它不給我適當的平均。那麼,我怎樣才能以正確的方式添加學生的成績呢?
有什麼特別的原因,試圖用手球陣列時,你可以用列表的列表,並得到這一切通過LINQ? – Mark
您在循環外部和循環的每次執行中設置'student [i] = new ...',但不在循環中使用'j'。 'Convert.ToInt32(student [i])'傳遞內部數組作爲對象,我認爲應該拋出一個異常,因爲int []不是'IConvertible'。我認爲你的意思是'學生[i] [j] = Convert.ToInt32(Console.ReadLine()); count + = student [i] [j];'當我們已經知道這個值是一個'int'時,不需要在第二行調用Convert。你可能應該使用'int.Parse()'或甚至更好的'int.TryParse()',這樣你可以處理錯誤的輸入。 – pinkfloydx33
不需要在方法頂部聲明循環變量。它們的範圍應該是循環條件。也給你的其他變量有意義的名字。 –