c# - 在 c# 中,我想在每次另一个整数增加一定数量时增加一个整数

标签 c# integer

我正尝试在 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/

相关文章:

c# - 带有文本框的 ASP.NET 动态 ASP 表 - 在 ViewState 中保存值

c# - C#中字符串和StringBuilder的区别

C# Core 1.1 Web API 接收 zip 文件

c# - 为什么模运算符 (%) 结果在 C# 中隐式转换到左侧而不是右侧?

java - for循环输入整数和小数

c# - 将方法作为构造函数的参数传递

c# - 在 IL 中隐藏接口(interface)的公共(public)成员

javascript - 如何在 JavaScript 中将整数转换为 float ?

C# "Integral constant is too large"- Int32 类型的整数变量太大

c - 根据素数对整数进行排序