c# -循环结束的结果

本文关键字:结果 结束 循环 | 更新日期: 2023-09-27 18:10:54

我将尽我所能解释这一点,所以请耐心等待。我正在制作一款游戏,基本上有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语句中,因此,一旦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);

c# -循环结束的结果

不只是从顶部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,以便您可以在此方法中调整剩余的码)