C //练习 5-8 函数day_of_year和month_day中没有进行错误检查,请解决该问题。

发布时间:2024年01月11日

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;
}
文章来源:https://blog.csdn.net/navicheung/article/details/135519191
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。