我正在编写一个程序,将不同的学生放在不同的教室。我在弄清楚如何在 C# 和一般编程中使用概率时遇到了一些困难。我希望成为 Alpha 学生的概率为 5%,成为 Omega 学生的概率为 10%,成为 Nightwalkers 学生的概率为 60%。我不明白要输入什么数字。我现在的方法:
public string AssignClassroom()
{
int rand = random.Next(0, 100);
{
if (rand < 5) // or >95%?
{
student.Classroom = "Alpha";
}
if (rand < 10) // or >90?
{
student.Classroom = "Omega";
}
if (rand < 60) // or >40?
{
student.Classroom = "Nightwalkers";
}
}
}
Run Code Online (Sandbox Code Playgroud)
您应该将 s中的数字相加if:
if (rand < 5) {
student.Classroom = "Alpha";
}
else if (rand < 10 + 5)
{
student.Classroom = "Omega";
}
else if (rand < 60 + 10 + 5)
{
student.Classroom = "Nightwalkers";
}
Run Code Online (Sandbox Code Playgroud)
请注意,这5, 10, 60是差异:
0 .. 5 .. 15 .. 75
| 5 | | | -> 5% top students go to the 1st class
| 10 | | -> 10% next go to the 2nd
| 60 | -> 60% goes to the 3d
Run Code Online (Sandbox Code Playgroud)