C# - 循环结束结果

时间:2015-09-01 16:33:15

标签: c#

我会尽力解释这一点,所以请耐心等待。我正在制作游戏,基本上还有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 if statment中,   因此有可能超过数字&#39; 100&#39;一旦yardsLeft = 0

那么如果它确实进入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);

1 个答案:

答案 0 :(得分:0)

不要只返回顶部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;
}

你也可以重做这个来提供一个字符串,说明Touchdown是否得分。 (让yardsLeft参数为ref,以便您可以调整此方法中的剩余码数。)