这个问题引起了我的兴趣所以我继续写了一个测试项目C#
.据我所知,它必须进行测试才能确定.
这是代码:
string strTime = "10:15:00"; DateTime dt = DateTime.ParseExact(strTime, "HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); int nHourDegrees = (360 / 12) * dt.Hour; int nMinuteDegrees = (360 / 60) * dt.Minute; int nSecondDegrees = (360 / 60) * dt.Second; if (nHourDegrees > nMinuteDegrees) { int nArea1 = nHourDegrees - nMinuteDegrees; int nArea2 = 360 - nArea1; bool bArea1IsBigger = (nArea1 >= nArea2); if (nSecondDegrees <= nHourDegrees && nSecondDegrees >= nMinuteDegrees) { //Second hand lies in area1 if (bArea1IsBigger) { Console.WriteLine("Second hand is in the larger area"); } else { Console.WriteLine("Second hand is in the smaller area"); } } else { if (bArea1IsBigger) { Console.WriteLine("Second hand is in the smaller area"); } else { Console.WriteLine("Second hand is in the larger area"); } } } else if (nMinuteDegrees > nHourDegrees) { int nArea1 = nMinuteDegrees - nHourDegrees; int nArea2 = 360 - nArea1; bool bArea1IsBigger = (nArea1 >= nArea2); if (nSecondDegrees <= nMinuteDegrees && nSecondDegrees >= nHourDegrees) { //Second hand lies in area1 if (bArea1IsBigger) { Console.WriteLine("Second hand is in the larger area"); } else { Console.WriteLine("Second hand is in the smaller area"); } } else { if (bArea1IsBigger) { Console.WriteLine("Second hand is in the smaller area"); } else { Console.WriteLine("Second hand is in the larger area"); } } } else { if (nSecondDegrees == nHourDegrees) { Console.WriteLine("Second hand is on both of the other hands"); } else { Console.WriteLine("Second hand is in the ONLY area"); } }
我们的想法是找到时针和分针之间的区域.然后检查秒针是否在此区域内.我们还将这个区域与另一个区域进行比较,然后我们可以很容易地推断出秒针是否在两者中较小或较大.
注意:可以对代码进行一些改进:
它可以明显缩短 - 我没有这样做,因为它主要是测试/证明如何做到这一点
如果超时(即24小时不是12小时),则必须进行更改.即减去12
如果时间转到12/60/60而不是回到0,则必须手动完成
可以添加常量以消除对幻数的需要
与上面类似,但常见的计算360 / 12
可以移动到常量
它可以分解为单独的方法以提高可读性
可以移动到辅助方法即 bool IsInLargerArea(string timeString)
当区域大小相同时需要添加大小写,此时我假设Area1
它们相等即大>=
(即大于或等于)
添加检查以确保straTimes
阵列只有3个部分
还有一些我没有想过的事情