本文主要是介绍C //练习 5-8 函数day_of_year和month_day中没有进行错误检查,请解决该问题。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C程序设计语言 (第二版) 练习5-8
练习 5-8 函数day_of_year和month_day中没有进行错误检查,请解决该问题。
注意:代码在win32控制台运行,在不同的IDE环境下,有部分可能需要变更。
IDE工具:Visual Studio 2010
代码块:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>static char daytab[2][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};int day_of_year(int year, int month, int day){int i, leap;if(year < 0){printf("Year Error!\n");return -1;}if(month < 1 || month > 12){printf("Month Error!\n");return -1;}leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){if(day < 1 || day > 31){printf("Day Error!\n");return -1;}}else if(month == 4 || month == 6 || month == 9 || month == 11){if(day < 1 || day > 30){printf("Day Error!\n");return -1;}}else{if(leap == 1){if(day < 1 || day > 29){printf("Day Error!\n");return -1;}}else{if(day < 1 || day > 28){printf("Day Error!\n");return -1;}}}for(i = 1; i < month; i++){day += daytab[leap][i];}return day;
}void month_day(int year, int yearday, int *pmonth, int *pday){int i, leap;if(year < 0){printf("Year Error!\n");return;}leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;for(i = 1; yearday > daytab[leap][i]; i++){yearday -= daytab[leap][i];}*pmonth = i;*pday = yearday;
}int main(){printf("The day is No.%d day.\n", day_of_year(2024, 1, 15));int *month = (int*)malloc(sizeof(int));int *day = (int*)malloc(sizeof(int));month_day(2024, 35, month, day);printf("No.%d day in %d is %d/%d/%d\n", 35, 2024, 2024, *month, *day);free(month);free(day);system("pause");return 0;
}
这篇关于C //练习 5-8 函数day_of_year和month_day中没有进行错误检查,请解决该问题。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!