# 怎么用C#實現打漁曬網問題
## 問題背景與需求分析
"打漁曬網"是一個經典的編程練習題,源于中國古代漁民的工作模式:三天打漁,兩天曬網。我們需要通過程序計算某一天是處于"打漁"還是"曬網"周期。
**問題需求**:
1. 輸入一個特定日期
2. 計算從固定起始日期到該日期的總天數
3. 根據總天數判斷是"打漁"還是"曬網"
4. 5天為一個周期(前3天打漁,后2天曬網)
## 解決方案設計
### 核心算法
1. **日期差值計算**:計算兩個日期之間的天數差
2. **周期判斷**:對總天數取模5,余數為1-3打漁,4-0曬網
### 技術要點
- DateTime日期的處理
- 閏年判斷邏輯
- 循環與條件判斷
## C#完整實現代碼
```csharp
using System;
class FishingSchedule
{
static void Main(string[] args)
{
// 設置固定起始日期(示例:2020年1月1日)
DateTime startDate = new DateTime(2020, 1, 1);
Console.WriteLine("請輸入要查詢的日期(格式:yyyy-MM-dd):");
string input = Console.ReadLine();
try
{
DateTime targetDate = DateTime.Parse(input);
if (targetDate < startDate)
{
Console.WriteLine("輸入日期不能早于起始日期!");
return;
}
int totalDays = CalculateTotalDays(startDate, targetDate);
string result = JudgeFishingOrDrying(totalDays);
Console.WriteLine($"從{startDate:yyyy-MM-dd}到{targetDate:yyyy-MM-dd}共經歷了{totalDays}天");
Console.WriteLine($"這一天是:{result}");
}
catch (FormatException)
{
Console.WriteLine("日期格式不正確!");
}
}
// 計算兩個日期之間的天數差
static int CalculateTotalDays(DateTime start, DateTime end)
{
return (end - start).Days;
}
// 判斷打漁還是曬網
static string JudgeFishingOrDrying(int days)
{
int remainder = days % 5;
return remainder switch
{
1 or 2 or 3 => "打漁",
_ => "曬網"
};
}
}
DateTime startDate = new DateTime(2020, 1, 1);
DateTime targetDate = DateTime.Parse(input);
DateTime
結構處理日期Parse
方法將字符串轉換為日期對象return (end - start).Days;
int remainder = days % 5;
return remainder switch
{
1 or 2 or 3 => "打漁",
_ => "曬網"
};
測試日期 | 預期結果 | 實際結果 |
---|---|---|
2020-01-01 | 打漁 | 打漁 |
2020-01-04 | 曬網 | 曬網 |
2020-01-06 | 打漁 | 打漁 |
2021-02-28 | 曬網 | 曬網 |
class FishingConfig
{
public int FishingDays { get; set; } = 3;
public int DryingDays { get; set; } = 2;
}
static string JudgeStatus(int days, FishingConfig config)
{
int cycle = config.FishingDays + config.DryingDays;
int remainder = days % cycle;
return remainder <= config.FishingDays && remainder != 0
? "打漁" : "曬網";
}
static bool ValidateDate(string input, out DateTime date)
{
return DateTime.TryParseExact(
input,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date);
}
Q1:為什么起始日期要固定? A:因為這是一個相對周期問題,需要參考基準點來計算總天數。
Q2:如何處理跨年的日期計算? A:DateTime的減法運算會自動處理閏年和月份天數差異,無需特殊處理。
Q3:如果輸入日期早于起始日期怎么辦? A:程序中已添加校驗,會提示錯誤信息。
通過這個案例我們學會了: 1. C#中DateTime的基本操作 2. 時間跨度的計算方法 3. 周期問題的通用解決思路 4. 控制臺程序的輸入輸出處理
完整項目代碼已上傳至GitHub:示例倉庫鏈接
提示:實際開發中應考慮添加更多異常處理,如空值檢查、日期范圍驗證等。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。