2016-10-29 59 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(); 
     } 
    }