我的代码是用户需要在其间输入标记的位置,然后如果标记不在0到100之间,它必须再次询问,我得到了它的工作,但现在问题陈述:调整上述程序也计算大于或等于50的标记数。
我该怎么做,我已经尝试声明计数整数0但我不确定如何 实现这一点。
这是我的代码:
static void Main(string[] args)
{
int total = 0;
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;
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.ReadLine();
}
答案 0 :(得分:2)
首先,我建议提取方法:不要将所有内容都塞进一个Main
中:
private static int readMark() {
Console.WriteLine("Enter your mark");
int result = 0;
while (true)
if (!int.TryParse(Console.ReadLine(), out result))
Console.WriteLine("Incorrect syntax, enter your mark again");
else if (result < 0 || result > 100)
Console.WriteLine("Mark should be in [0..100] range, enter your mark again");
else
return result;
}
然后让我们将所有标记读入集合,比如一个数组:
static void Main(string[] args) {
int[] marks = new int[5];
for (int i = 0; i < marks.Length; ++i)
marks[i] = readMark();
}
现在是统计的时候了。通常我们使用 Linq :
static void Main(string[] args) {
...
double average = marks.Average();
int sum = marks.Sum();
int countGreaterThan50 = marks.Count(item => item > 50);
但我们可以为此设置一个好的for
/ foreach
循环:
static void Main(string[] args) {
...
int total = 0;
countGreaterThan50 = 0;
for (int i = 0; i < marks.Length; ++i) {
total += marks[i];
if (marks[i] > 50)
countGreaterThan50 += 1;
}
// (double) total - be careful with integer division:
// 91 / 5 == 18 when 91.0 / 5 == 18.2
double average = ((double) total) / marks.Length;
答案 1 :(得分:1)
static void Main(string[] args)
{
int total = 0;
int gt50Count = 0;
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("Greater or equal to 50 count = " + gt50Count);
Console.ReadLine();
}
答案 2 :(得分:1)
我会更改您检查标记对while循环无效的方式。只有在检查时,如果用户连续插入无效值,您的代码将接受它。
static void Main(string[] args)
{
int total = 0;
int marksAbove50Count = 0;
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
while (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) marksAbove50Count++;
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Marks above 50 count: " + marksAbove50Count);
Console.ReadLine();
}