2016-10-29 57 views
-1

在程序中遇到一些麻烦,目前在编程课程的第二周如此不好,如果这不是最好的地方问。c#要检查一年是否是没有日期时间的闰年

class Program 
{ 
    static void Main(string[] args) 
    { 
     int a; 
     Console.WriteLine("Enter the year"); 
     a = int.Parse(Console.ReadLine()); 
     { 
      if ((a % 4) == 0) 
       Console.WriteLine("It's a leap year."); 
      else 
       Console.WriteLine("It's not a leap year."); 
     } 
     Console.ReadLine(); 
    } 
} 

在这方面有很多麻烦。

+1

为什么有'{} ''围绕'if'语句阻止? – Benj

+0

你有做过什么研究吗?用于检查整数是闰年的编程公式可以在Google – techydesigner

回答

6

rules for a leap year are

  • 年份可被4平分秋色;
  • 如果年份可以平均除以100,那不是闰年,除非;
  • 年份也可以被400整除。然后是闰年。

希望这可以帮助你找出将它翻译成代码的方法。由于这是作业,我不会发布实际的代码,但我会给你一些提示。为了组合两个支票,使用&&算子来表示AND,||以表示OR!以表示NOT

最终的公式看起来像

if (a%4 == 0 __ (!(_____ == 0) __ (______ == 0)) 

您将需要填补空白的自己。

+0

上轻松获得,您应该在问题编辑您的评论然后 – Benj

+1

@Benj Refresh,评论已被删除一段时间。 –

-2

DateTime类具有IsLeapYear方法

您可以使用如下:

if(DateTime.IsLeapYear(a)) 
    { 
    Console.WriteLine("It's a leap year") 
    } 
    else 
    { 
    Console.WriteLine("It's not a leap year") 
    } 
+3

这很可能是一项家庭作业任务,教授学生如何组合多个逻辑测试。他甚至明确表示他不能在标题 –

+0

中使用IsLeapYear检查。问题清楚地询问*没有DateTime *。如何以* DateTime类*相关开始的答案? –

1

这应该做的。如果你了解这个代码,你已经清楚地赢得了作业点......因为它真的有效:-)

private static Boolean IsLeapYear(Int32 year) 
    { 
     if (-1 != ~(year & (1 | 1 << 1))) return false; 

     if (0 == ((year >> 2) % 0x0019)) 
     { 
      if (0 == (year/0x0010) % 0x0019) return true; 
      return false; 
     } 

     return true; 
    } 
1

你可以试试这个..

class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Please Enter The Year:"); 
      int year = int.Parse(Console.ReadLine()); 
      if (year%400 == 0 || (year%4 == 0 && year%100 != 0)) 
      { 
       Console.WriteLine("Leap Year"); 
      } 
      else 
      { 
       Console.WriteLine("Not Leap Year"); 
      } 
      Console.ReadLine(); 
     } 
    }