for語句和switch語句分別實現
文章目錄
前言
一、用switch做
二、用for循環做
?編輯
總結
前言
用兩種不同的方法求解【輸入某年某日,判斷這是這一年的第幾天】
一、用switch做
代碼如下(示例):
int main()
{int y, m, d, count, k;scanf("%d %d %d", &y, &m, &d);if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)k = 1;else k = 0;count = d;switch (m - 1){case 11:count = count + 30;case 10:count = count + 31;case 9:count = count + 30;case 8:count = count + 31;case 7:count = count + 31;case 6:count = count + 30;case 5:count = count + 31;case 4:count = count + 30;case 3:count = count + 31;case 2:count = count + 28+k;case 1:count = count + 31;}printf("%d年%d月%d日是%d年的第%d天", y, m, d, y, count);return 0;
}
該處不能把count=d放在switch里面,switch語句執行時會先匹配case,若放在switch語句里面,會報錯,出現未初始化變量count
如下代碼及運行結果:
二、用for循環做
代碼如下(示例):
int main()
{int i,y, m, d, countday, k;int mouth[12] = { 0,31,28,31,30,31,30,31,31,30,31,30 };scanf("%d %d %d", &y, &m, &d);if ((y % 4 == 0 & y % 10 != 0) || y % 400 == 0)k = 1;else k = 0;mouth[2] = mouth[2] + k;countday = d;for (i = 1; i < m; i++)countday = countday + mouth[i];printf("%d年%d月%d日是%d年的第%d天", y, m, d, y, countday);return 0;
}
如下代碼及運行結果:?