2017-06-07 33 views
-1

剛剛開始學習C#,並在課堂上做了'閏年'。我們想出了這個解決方案。但它只允許一次檢查一年。是否有一個很好的方法來一次檢查更多?假設我需要檢查10個不同的年份,如果他們跳躍或不跳躍。我能想到的是複製塊並給出新的變量。如何在'閏年'中檢查一年以上

int a = int.Parse(Console.ReadLine()); 

bool div1 = a % 4 == 0; 
bool div2 = a % 100 != 0; 
bool div3 = a % 400 == 0; 

if ((div1 && div2) || div3) 
{ 
    Console.WriteLine($"{a} is a leap year"); 
} 
else 
{ 
    Console.WriteLine($"{a} is not a leap year"); 
} 
+0

你知道'for'循環是什麼嗎? – dan04

+1

我明白你寫了這個練習,但請知道在現實世界中,你應該使用'DateTime.IsLeapYear'內置函數。我不會讓任何代碼審查通過手工製作的閏年檢查。 –

+0

還沒有。我可能會提前一點。但是如果你想檢查另一個隨機年份,從頭開始運行一切都有點不舒服。因此,這個問題。 – Katerina

回答

0

您可以閱讀多年的字符串(例如:1991,1992,2001,2004),然後用string.split(',')的字符串分割到數組。循環訪問數組以檢查閏年。

1

這樣做的一種方法是編寫一個函數,如果int代表閏年,則返回int int並返回true。例如,下面的方法使用您在上面寫的代碼的簡化,一個行版本:

public static bool IsLeapYear(int year) 
{ 
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; 
} 

然後,你可以從用戶那裏得到一串年(在這個例子中,我們使用一個逗號的年 - 分隔列表)分裂年到一個數組(在逗號字符),並調用每年這種方法在一個循環:

private static void Main() 
{ 
    // Get a list of years from the user 
    Console.Write("Enter some years separated by commas: "); 
    var input = Console.ReadLine(); 

    // Split the user input on the comma character, creating an array of years 
    var years = input.Split(','); 

    foreach (var year in years) 
    { 
     bool isLeapYear = IsLeapYear(int.Parse(year)); 

     if (isLeapYear) 
     { 
      Console.WriteLine("{0} is a leap year", year); 
     } 
     else 
     { 
      Console.WriteLine("{0} is not a leap year", year); 
     } 

    } 
    Console.WriteLine("\nDone!\nPress any key to exit..."); 
    Console.ReadKey(); 
} 

輸出

enter image description here


如果你想一次輸入一個,你可以做的另一件事就是要求用戶在一個循環內輸入新的一年,並在輸入一個整數後給他們一個答案。這裏有一個例子,在這裏我也添加了名爲GetIntFromUser另一個函數,這迫使他們進入一個有效的整數(它不停地問,直到輸入一個):

private static void Main() 
{ 
    // In this loop, ask for a year and tell them the answer 
    while (true) 
    { 
     int input = GetIntFromUser("Enter a year to check: "); 
     string verb = IsLeapYear(input) ? "is" : "is not"; 
     Console.WriteLine($"{input} {verb} a leap year.\n"); 
    } 
} 

public static int GetIntFromUser(string prompt) 
{ 
    int input; 

    // Show the prompt and keep looping until the input is a valid integer 
    do 
    { 
     Console.Write(prompt); 
    } while (!int.TryParse(Console.ReadLine(), out input)); 

    return input; 
} 

public static bool IsLeapYear(int year) 
{ 
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; 
} 

輸出

enter image description here

1

首先,將現有代碼放入函數中,以便重用:

public bool IsLeapYear(int year) 
{ 
    bool div1 = year % 4 == 0; 
    bool div2 = year % 100 != 0; 
    bool div3 = year % 400 == 0; 
    return ((div1 && div2) || div3); 
} 

然後讓我們說你有一組40歲的數組:

//don't worry about how this works right now. 
// just know it gives you an array with 40 years starting in 1980 
int[] years = Enumerable.Range(1980, 40).ToArray(); 

您可以檢查所有的人都像這樣:

foreach (int year in years) 
{ 
    if (IsLeapYear(year)) 
    { 
     Console.WriteLine($"{year} is a leap year"); 
    } 
    else 
    { 
     Console.WriteLine($"{year} is not a leap year"); 
    } 
} 
1

您可以使用LINQ。

var years = new int[] { 1999, 2000, 2001, 2002 }; //etc... 

Console.WriteLine(String.Join(Environment.NewLine, years 
    .Select(y => $"{y} {(DateTime.IsLeapYear(y) ? "is" : "is not")} a leap year") 
    .ToArray())); 
+0

這有效......但在提問的上下文中這不是一個非常有用的答案。 –

0

首先,如果您使用的是int.Parse(),您應該在try-catch塊中使用它。否則,當用戶輸入無意義的內容時,程序每次都會崩潰。

第二,如果你想實現爲研究目的使用您自己的方法 - 它`沒關係,但你可以使用的DateTime結構,其具有IsLeapYear():

// Summary: 
    //  Returns an indication whether the specified year is a leap year. 
    // 
    // Parameters: 
    // year: 
    //  A 4-digit year. 
    // 
    // Returns: 
    //  true if year is a leap year; otherwise, false. 
    // 
    // Exceptions: 
    // T:System.ArgumentOutOfRangeException: 
    //  year is less than 1 or greater than 9999. 

因此,實現如下:

class LeapYear 
{ 
    static void Main(string[] args) 
    { 
     for (int input = 0; input < 10;) // Ask user until he enters year 10 times correctly 
     { 

      Console.Write("Please enter a year: "); 

      try 
      { 
       int year = int.Parse(Console.ReadLine()); 

       if (DateTime.IsLeapYear(year)) 
       { 
        Console.WriteLine($"{year} is leap"); 
        input++; 
       } 
       else 
        Console.WriteLine($"{year} is not leap"); 
      } 

      catch (ArgumentOutOfRangeException) 
      { 
       Console.WriteLine("Argument Out Of Range"); 
      } 

      catch (FormatException) 
      { 
       Console.WriteLine("Bad Format"); 
      } 

      catch (OverflowException) 
      { 
       Console.WriteLine("Overflow"); 
      } 

     } 

     Console.WriteLine("Press any key to exit..."); 
     Console.ReadKey(); 

    } 
}