循环时基本c#

时间:2016-06-11 06:45:02

标签: c# visual-studio while-loop

我有问题要解决2个假设的oppenents正在决斗RPG风格。我被要求给他们惠普,每一轮循环惠普都会失去他们的oppenent打他们的东西。我对它有基本的了解,但我的数字不断重复。在Visual Studios工作15.提前感谢!

/*Fighter 1 is Charlie The Unicorn
 *Fighter 2 is Nyan Cat
 *Fighter 1 has 100 HP
 *Fighter 2 has 150 HP
 *Fighter 1 can hit as hard as 15HP each turn
 *Fighter 2 can hit as hard as 10HP each turn
*/

//Who wins the fight

int fighterOneHealth = 100;
int fighterTwoHealth = 150;
Random randomizer = new Random();
while (fighterOneHealth > 0 || fighterTwoHealth > 0)
{      
    int fOneRandomHit;
    int fTwoRandomHit;
    fOneRandomHit = randomizer.Next(0, 15);
    fTwoRandomHit = randomizer.Next(0, 10);
    int fightOneHpLoss = fighterOneHealth - fTwoRandomHit;
    int fightTwoHpLoss = fighterTwoHealth - fOneRandomHit;
    Console.WriteLine("After attack: Charlie the Unicorn HP: {0}, Nyan Cat HP: {1}", fightOneHpLoss, fightTwoHpLoss);
}

1 个答案:

答案 0 :(得分:6)

你在循环中声明 new 变量:

int fightOneHpLoss = fighterOneHealth - fTwoRandomHit;
int fightTwoHpLoss = fighterTwoHealth - fOneRandomHit;

...但你永远不会修改那些代表球员当前健康状况的变量。你根本不需要那些额外的变量 - 你只需要降低健康状况:

fighterOneHealth -= fTwoRandomHit;
fighterTwoHealth -= fOneRandomHit;
Console.WriteLine("After attack: Charlie the Unicorn HP: {0}, Nyan Cat HP: {1}",
    fighterOneHealth, fighterTwoHealth);