我正在尝试编写一个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();
}
}
}
但我有问题,因为它没有给我正确的平均值。那么如何以正确的方式添加学生的成绩呢?
答案 0 :(得分:0)
更改此行:
int n,m,i,j,count=0,avg;
为:
int n,m,i,j,count=0;
double avg;
和这一行:
avg = count / m ;
到
avg = (double)count / (double)m ;
count=0;
答案 1 :(得分:0)
另外:您为此处的每个成绩输入创建了新的成绩数组
student[i] =new int[] {Convert.ToInt32(Console.ReadLine())};
该行应为
student[i][j-1] =Convert.ToInt32(Console.ReadLine());
第二
count +=Convert.ToInt32(student[i]);
应该是
count += student[i][j-1];
答案 2 :(得分:0)
我想使用锯齿状数组是你的任务的必要条件,所以我会坚持使用OP。如果不是,您可以使用List<List<int>>
作为马克建议的等级。
我尝试对代码进行微小的更改。
问题是,您缺少声明阵列中的“锯齿状”部分,并且在尝试添加总数时,您遇到了一些问题。
static void Main(string[] args)
{
int n, m, i, j, count;
Console.WriteLine("please enter the number of students");
n = Convert.ToInt32(Console.ReadLine());
int[][] student = new int[n][];
for (i = 0; i < n; i++)
{
count = 0;
Console.WriteLine("how many grades does student number " + (i+1) + " have?");
m = Convert.ToInt32(Console.ReadLine());
student[i] = new int[m];
Console.WriteLine("please enter student number " + (i+1) + "'s grades");
for (j = 0; j < m; j++)
{
student[i][j] = Convert.ToInt32(Console.ReadLine());
count += Convert.ToInt32(student[i][j]);
}
var avg = count / m;
Console.WriteLine("the student number " + i + "'s average is " + avg);
}
Console.ReadKey();
}
答案 3 :(得分:0)
立即修改代码
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+1];
Console.WriteLine("please enter student number " + i + "'s grades");
for (j = 1; j <= m; j++)
{
student[i][j] = Convert.ToInt32(Console.ReadLine());
count += Convert.ToInt32(student[i][j]);
}
avg = count / m;
Console.WriteLine("the student number " + i + "'s average is " + avg);
avg = 0;
}
Console.ReadKey();
}