C#输出不正确
这是我的代码,它的目的是输入学生人数,然后询问每个学生的姓名,每个学生输入5分。。。我的问题是,当我运行代码时,例如,如果我输入2名学生,它会询问他们的姓名,但随后会询问他们的分数10次,而不是5次。因此,它输出的是输入分数的总次数,而不是每个学生的5次,如何解决这个问题C#输出不正确,c#,output,C#,Output,这是我的代码,它的目的是输入学生人数,然后询问每个学生的姓名,每个学生输入5分。。。我的问题是,当我运行代码时,例如,如果我输入2名学生,它会询问他们的姓名,但随后会询问他们的分数10次,而不是5次。因此,它输出的是输入分数的总次数,而不是每个学生的5次,如何解决这个问题 int total = 0; int gt50Count = 0; Console.WriteLine("How many students are there?");
int total = 0;
int gt50Count = 0;
Console.WriteLine("How many students are there?");
int students = int.Parse(Console.ReadLine());
for (int y = 1; y <= students; y++)
{
Console.WriteLine("Enter student name");
string name = Console.ReadLine();
for (int ask = 1; ask <= students; ask++)
{
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
if (mark >= 50)
{
gt50Count++;
}
}
}
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Greather or equal to 50 count = " + gt50Count);
Console.ReadLine();
}
}
int-total=0;
int GT50计数=0;
控制台。WriteLine(“有多少学生?”);
int students=int.Parse(Console.ReadLine());
对于(int y=1;y,再次在学生上嵌套循环
for (int ask = 1; ask <= students; ask++) //why this loop ?
{
..
for (int x = 1; x <= 5; x++) // 2 x 5 = 10
{
.... //ask for mark 10 times
}
}
for(int ask=1;ask您在那里有一个额外的for循环,只需要删除它。另外,我假设您希望获得输入的每个学生的总和和平均值。为此,您需要在第一个for循环的底部包含该功能。请查看此重构代码:
int total = 0;
int gt50Count = 0;
Console.WriteLine("How many students are there?");
int students = int.Parse(Console.ReadLine());
for (int y = 1; y <= students; y++)
{
Console.WriteLine("Enter student name");
string name = Console.ReadLine();
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
if (mark >= 50)
{
gt50Count++;
}
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Greather or equal to 50 count = " + gt50Count);
Console.ReadLine();
}
int-total=0;
int GT50计数=0;
控制台。WriteLine(“有多少学生?”);
int students=int.Parse(Console.ReadLine());
对于(整数y=1;y=50)
{
gt50Count++;
}
}
Console.WriteLine(“总和=”+总计);
双平均=(总计/5)*1.00;
Console.WriteLine(“average=“+average”);
Console.WriteLine(“大于或等于50 count=“+gt50Count”);
Console.ReadLine();
}
对于
循环有3个,第二个是多余的,应该删除。