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;
}
如下代码及运行结果: