原始問題
double y;
Console.WriteLine("請輸入年份:");
y = Convert.ToDouble(Console.ReadLine());
if (y % 400 == 0)
{
Console.WriteLine("該年份為閏年.");
}
else if ((y % 4 == 0) && (y % 100 != 0))
{
Console.WriteLine("該年份為閏年.");
}
else if ((y % 4 > 0) && (y % 100 > 0))
{
Console.WriteLine("該年份非閏年.");
}
Console.ReadLine();
錯誤原因
- 使用
double 儲存年份,進行模運算(%)可能產生浮點數精度問題,應使用 int。
- 缺少完整的
else 分支,例如 2300 年既不能被 400 整除,也不能被 4 且不被 100 整除(實際上 2300 能被 4 整除也能被 100 整除,但不能被 400 整除,屬於平年),因此沒有任何分支符合,導致沒有輸出。
修正範例
int year = Convert.ToInt32(Console.ReadLine());
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
{
Console.WriteLine("該年份為閏年.");
}
else
{
Console.WriteLine("該年份非閏年.");
}