C# CS0019&x9;操作员'+=';无法应用于类型为';int';和';布尔';
我目前正在编写一个简单的骰子游戏,我遇到了一个让我困惑的错误,这是我的代码C# CS0019&x9;操作员'+=';无法应用于类型为';int';和';布尔';,c#,runtime-error,operators,C#,Runtime Error,Operators,我目前正在编写一个简单的骰子游戏,我遇到了一个让我困惑的错误,这是我的代码 foreach (var die in Dice.rolls) { Console.WriteLine(die.ToString()); } if (player.score += score >= goal) { playing = false; Console.WriteLine("{0} has won the game!", player.name); Console.Wri
foreach (var die in Dice.rolls)
{
Console.WriteLine(die.ToString());
}
if (player.score += score >= goal)
{
playing = false;
Console.WriteLine("{0} has won the game!", player.name);
Console.WriteLine("Please press any key to end the game");
Console.ReadKey();
}
else
{
player.score += score;
}
我遇到的问题是线路:
if (player.score += score >= goal)
抛出一个错误,告诉我不能在int和bool上使用它,但是if语句中的所有变量都是int。下面还有几行:
player.score += score;
没有给我任何错误。可能是操作的优先级吗?尝试:
if ( (player.score += score) >= goal)
虽然,在我看来,你应该:
a) 将其分成两行:
player.score += score;
if (player.score >= goal)
或b)将行更改为:
if (player.score + score > goal)
目前来看,这可能是有意的,如果不是>=目标,则player.score最终会将分数添加两次,因为它将作为if的一部分添加,然后作为else的主体添加。这是一个操作符优先级的问题。比较运算符>=具有更高的优先级,因此本质上您试图通过布尔比较的结果来增加
player.score
您可以使用括号来修复此问题或简化表达式,例如
player.score += score;
if (player.score >= goal)
您可以在此处查找更多信息您不能在同一行中同时执行这两个操作。只需先加上分数,然后进行比较。你告诉编译器要做的是求解score>=goal并将其添加到player.score中,从而得到错误。是的,这是操作的优先级,cheers palIt将其分成两行更为清晰。试图编写简洁的代码,在其中增加并检查一行中的变量,将来可能会成为bug的来源。