C#:使用模数学递减时钟

Sin*_*tic 6 c# math clock modulo

试图用手模拟24小时时间的翻转(使用数学与使用时间跨度类).递增部分很容易弄清楚如何从23:00到0:00滚动,但从另一个方向走向结果却变得非常混乱.这是我到目前为止所拥有的:

static void IncrementMinute(int min, int incr)
{
    int newMin = min + incr,
                hourIncrement = newMin / 60;

    //increment or decrement the hour
    if((double)newMin % 60 < 0 && (double)newMin % 60 > -1)
        hourIncrement = -1;

    Console.WriteLine("Hour increment is {0}: ", hourIncrement);
}
Run Code Online (Sandbox Code Playgroud)

我发现的问题是当倒退时,如果模数在数字之间,它将不会正确递减.示例:它是12:00并且您减去61分钟,我们知道时间将是10:59,因为小时应该从12:00返回到11:59,然后从11:00返回到10:59 不幸的是我计算它的方式:在这种情况下newMin%60,只抓取第一个小时回滚,但由于第二次回滚在技术上是-1.0166作为余数,并且因为mod只返回一个整数,所以它四舍五入.我确定我在这里缺少一些基本的数学,但有人可以帮助我吗?

编辑:我已经写了很多长短的方法.有些比其他人更接近,但我知道这比看起来更简单.我知道这个似乎有点"他正在做什么",但你应该能够基本看到我想做的事情.增加时钟并使其从23:59到0:00翻转很容易.向后看已经证明并不那么容易.

好的,这是带翻转的incrementMinute.简单.但试着倒退.不行.

static void IncrementMinute(int min, int incr)

        {
            int newMin = min + incr,
                hourIncrement = newMin / 60;

            min = newMin % 60;

            Console.WriteLine("The new minute is {0} and the hour has incremented by {1}", min, hourIncrement);
        }
Run Code Online (Sandbox Code Playgroud)

Dia*_*tis 2

我会选择更简单的东西

public class Clock
{
    public const int HourPerDay = 24;
    public const int MinutesPerHour = 60;
    public const int MinutesPerDay = MinutesPerHour * HourPerDay;

    private int totalMinutes;

    public int Minute
    {
        get { return this.totalMinutes % MinutesPerHour; }
    }

    public int Hour
    {
        get { return this.totalMinutes / MinutesPerHour; }
    }

    public void AddMinutes(int minutes)
    {
        this.totalMinutes += minutes;
        this.totalMinutes %= MinutesPerDay;
        if (this.totalMinutes < 0)
            this.totalMinutes += MinutesPerDay;
    }

    public void AddHours(int hours)
    {
        this.AddMinutes(hours * MinutesPerHour);
    }

    public override string ToString()
    {
        return string.Format("{0:00}:{1:00}", this.Hour, this.Minute);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用示例:

new Clock().AddMinutes(-1);    // 23:59
new Clock().AddMinutes(-61);   // 22:59
new Clock().AddMinutes(-1441); // 23:59
new Clock().AddMinutes(1);     // 00:01
new Clock().AddMinutes(61);    // 01:01
new Clock().AddMinutes(1441);  // 00:01
Run Code Online (Sandbox Code Playgroud)