我正尝试在 C# 中执行此任务。
我有 2 个整数... 积分总分 内部 ExtraLife
每当 TotalScore 增加至少 5 时,我想将“ExtraLife”增加 1 吗?
这是一个例子...
public void Example(int scored)
{
TotalScore += scored;
if (TotalScore > 0 && TotalScore % 5 == 0)
{
ExtraLife++;
// it seems that the ExtraLife will only increment if the
// total score is a multiple of 5.
// So if the TotalScore were 4 and 2 were passed
// in as the argument, the ExtraLife will not increment.
}
}
最佳答案
你可以这样做
class Whatever
{
private int extraLifeRemainder;
private int totalScore;
public int TotalScore
{
get { return totalScore; }
set
{
int increment = (value - totalScore);
DoIncrementExtraLife(increment);
totalScore = value;
}
}
public int ExtraLife { get; set; }
private void DoIncrementExtraLife(int increment)
{
if (increment > 0)
{
this.extraLifeRemainder+= increment;
int rem;
int quotient = Math.DivRem(extraLifeRemainder, 5, out rem);
this.ExtraLife += quotient;
this.extraLifeRemainder= rem;
}
}
}
private static void Main()
{
Whatever w = new Whatever();
w.TotalScore += 8;
w.TotalScore += 3;
Console.WriteLine("TotalScore:{0}, ExtraLife:{1}", w.TotalScore, w.ExtraLife);
//Prints 11 and 2
}
关于c# - 在 c# 中,我想在每次另一个整数增加一定数量时增加一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23926584/