[英]C# - Loop ending result
我将尽我所能来解释这个问题,所以请多多包涵。 我在做游戏,基本上有100码。 您从100开始,然后开始循环播放,生成数字并从100码中减去。 一旦数字达到0,循环就会停止。
看一下这段代码:
int yardsLeft = 100;
// this is on a loop until 'yardsLeft = 0'
if (yardsLeft >= 80)
{
// 10% chance of generating a number 80-100
// 20% chance of generating a number 40-80
// 70% chance of generating a number 1-40
// Say it hits the 10% chance and generates the number 85 - there's 15 yards left
// it will pass through the if statements entering the `if (yardsLeft < 40)` - say that hits 20 once more. at the end once the yardsLeft finally equals 0, the yards added up each loop will be over 100. in this case 120
-------------------------------
// but if the generated number generates a 70% chance and hits a number 1-20, it's going to stay in the `yardsLeft > 80` if statment-
// therefore having the potential to exceed the number '100' once the `yardsLeft = 0`
}
else if (yardsLeft >= 40 && yardsLeft <= 79) { } // this would activate if the 20% chance got generated
if (yardsLeft < 40)
{
// 10% chance of generating a number 30-39
// 20% chance of generating a number 10-29
// 70% chance of generating a number 1-9
}
我的问题:
如果生成的数字产生70%的机会并击中数字1-20,则它将停留在
yardsLeft > 80
如果声明)中,因此一旦yardsLeft = 0
,它就有可能超过数字'100'
那么,如果它确实输入了yardsLeft >= 80
,我如何确保它生成一个数字,最后生成的数字恰好是100
码(数字相加)
这是我的循环:
while (yardsLeft > 0)
{
int[] playResult = new int[i + 1];
playResult[i] = r.Next(1, 4);
switch (playResult[i])
{
case 1:
Console.WriteLine(BuffaloBills.QB + " hands it off to " + BuffaloBills.RB + " for a gain of " + Calculations.Play() + " yards. \n");
yardsLeft -= gained;
i++;
break;
case 2:
Console.WriteLine(BuffaloBills.QB + " passes it " + BuffaloBills.WR + " for a gain of " + Calculations.Play() + " yards. \n");
yardsLeft -= gained;
i++;
break;
case 3:
Console.WriteLine(BuffaloBills.QB + " doesn't find anyone open so he rushes for a gain of " + Calculations.Play() + " yards. \n");
yardsLeft -= gained;
i++;
break;
}
}
这是我的变量
public static Random r = new Random();
public static int gained;
public static int yardsLeft = 100;
public static int i = 0;
public static int chance = r.Next(1, 101);
不要只是从顶部的if / else if / else语句返回数字,而是要等到块的末尾再返回到那里。 这样一来,您就可以收集所有逻辑以进行计算。
private int Play(int yardsLeft) // Pass in the total yards left here
{
var yards = 0;
if (yardsLeft >= 80)
{
yards = // The result of your 10/20/70% calculation
}
else if (yardsLeft >= 40) { } // Same deal
else { } // Again, same as in the if
return yards > yardsLeft ? yardsLeft : yards;
}
您还可以对此进行重新处理以提供一个字符串,该字符串将说明是否已触地得分。 (将yardsLeft
参数设置为ref
以便您可以在此方法内调整剩余的码。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.