C# if 语句中的不同概率
C# Different probabilities in if statements
我正在写一个程序,我把不同的学生放在不同的教室里。我在弄清楚如何在 C# 和一般编程中使用概率时遇到了一些麻烦。我希望成为 Alpha 学生的概率为 5%,Omega 为 10%,Nightwalkers 为 60%。我不明白现在要输入什么数字 in.My 方法:
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";
}
}
}
你应该在if
秒中加起来:
if (rand < 5) {
student.Classroom = "Alpha";
}
else if (rand < 10 + 5)
{
student.Classroom = "Omega";
}
else if (rand < 60 + 10 + 5)
{
student.Classroom = "Nightwalkers";
}
请注意,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
我正在写一个程序,我把不同的学生放在不同的教室里。我在弄清楚如何在 C# 和一般编程中使用概率时遇到了一些麻烦。我希望成为 Alpha 学生的概率为 5%,Omega 为 10%,Nightwalkers 为 60%。我不明白现在要输入什么数字 in.My 方法:
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";
}
}
}
你应该在if
秒中加起来:
if (rand < 5) {
student.Classroom = "Alpha";
}
else if (rand < 10 + 5)
{
student.Classroom = "Omega";
}
else if (rand < 60 + 10 + 5)
{
student.Classroom = "Nightwalkers";
}
请注意,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