C#输出不正确

时间:2018-04-11 20:57:19

标签: c# output

这是我的代码,它的目的是输入学生人数,然后询问每个学生的名字,每个学生输入5分...我的问题是,当我运行代码时,例如,如果我输入2学生,它要求他们的名字,但然后要求他们的标记10次而不是5.所以它输出的总时间输入标记而不是每个学生5,我该如何解决?

        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();
    }
}

}

2 个答案:

答案 0 :(得分:1)

你再次对学生进行嵌套循环。

 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
    }
  }

答案 1 :(得分:0)

你有一个额外的for循环,只需要删除。另外,我假设你想要得到每个学生的总和和平均值。要做到这一点,您需要在第一个for循环的底部包含该功能。看看这个重构的代码:

type ClassConstructor<T> = new(...args: any[]) => T;

const mixin = <B extends ClassConstructor<HTMLElement>, T>(base: B, arg: T) => {
    return class extends base {
        prop: T = arg;
    };
};

const Test1 = mixin(HTMLElement, 10); // using inference
type Test1Prop = typeof (new Test1()).prop; // number

type MixinReturnType = ReturnType<typeof mixin>;
const Test2: MixinReturnType = mixin(HTMLElement, 10); // using explicit type annotation
type Test2Prop = typeof (new Test2()).prop; // {}