Table of contents
3. Solution 1 (switch statement)
foreword
C language exercises --- two methods of obtaining the number of days in a month, described from two aspects of switch statement and array.
提示:以下是本篇文章正文内容,下面案例可供参考
1. Problem description
describe:
KiKi wants to get the number of days in a certain year and month, please help him program it. Enter a year and a month to calculate how many days there are in this year and month.
Enter a description:
Multiple sets of input, one line has two integers, representing year and month respectively, separated by spaces.
Output description:
For each set of inputs, the output is one line, an integer indicating how many days there are in this year and month.
Example 1:
enter:
2008 2output:
29
2. Problem-solving ideas
Distribution of days per month:
month 1 2 3 4 5 6 7 8 9 10 11 12 normal year 31 28 31 30 31 30 31 31 30 31 30 31 leap year 31 29 31 30 31 30 31 31 30 31 30 31 Except that the number of days in February is different between ordinary years and leap years, everything else is the same. You can use switch and array to solve the problem.
3. Solution 1 (switch statement)
Using the switch statement, the case is divided into 1~12.
Case 1, 3, 5, 7, 8, 10, 12 days are all 31 days;
case 4, 6, 9, 11 days are all 3;
Case 2 is divided into normal year and leap year.
Code example:
int main() { int y = 0; int m = 0; while (scanf("%d%d", &y, &m) == 2) { switch(m) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: printf("%d\n",31); break; case 4: case 6: case 9: case 11: printf("30\n"); break; case 2: { if (((y % 4 == 0) && (y % 100) != 0) || (y % 400) == 0) printf("29\n"); else printf("28\n"); } } } return 0; }
4. Solution 2 (Array)
Store the days of the 12 months in the array in order, and add an element 0 to correspond to the subscript of the array.
Determines whether the year is a normal year or a leap year.
Code example:
int my_year(int y) { return (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)); } int main() { int y, m; int arr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 }; while ((scanf("%d %d", &y, &m)) == 2) { int day = arr[m]; if (my_year(y) && m == 2) { day++; } printf("%d\n", day); } return 0; }
4. Running results
at last
Happy time is always short. The above is what I want to talk about today. This article introduces the exercises that Comrade Xiao Zhao encountered in learning C language, and expresses its solution and implementation. Family members are welcome to criticize and correct. Comrade Xiao Zhao continues to update, the motivation for continuous learning is the support of Baozi with one button and three consecutive links~