软件测试(第2版)_Paul学习03_01——Ch2举例_02

2.3 NextDate函数

2.3.1 问题陈述

NextDate是一个有三个变量(月份、日期和年)的函数。函数返回输入日期后面的那个日期。变量月份、日期和年都是整数,且满足以下条件:

C1:1≤月份≤12

C2:1≤日期≤31

C3:1812≤年≤2012

对无效的输入日期,比如6月31日,或c1、c2、c3中的任意一个条件失败,则NextDate,都会产生一个输出,指示其为无效日期,或给出具体的无效原因,或笼统的给出"无效日期输入。"提示。

2.3.2 讨论

此例子的特点是说明另一种复杂性,输入变量之间的逻辑关系较复杂。

2.3.2 实现

C语言实现如下:

/*Improved version*/
#include <stdio.h>
int leapYear(int year)
{
	if((year % 100 != 0) && (year % 4 == 0))
	{
		return 1;
	}
	else if (year % 400 == 0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

int main(void)
{
	int tomorrowDay, tomorrowMonth, tomorrowYear;
	int day, month, year;
	int c1, c2, c3;
	do
	{
		printf("Enter today's date in the form MM DD YYYY");
		scanf("%d %d %d", &month, &day, &year);
		c1 = (1 <= day) && (day <= 31);
		c2 = (1 <= month) && (month <= 12);
		c3 = (1812 <= year) && (year <= 2012);
		if (!c1)
		{
			printf("Value of day not in range 1..31\n");
		}
		if (!c2)
		{
			printf("value of month not in range 1..12\n");
		}
		if (!c3)
		{
			printf("value of year not in range 1812..2012\n");
		}
	} while (!c1 || !c2 || !c3 );

	tomorrowMonth = month;
	tomorrowYear = year;
	switch (month)
	{
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
			if (day < 31)
			{
				tomorrowDay = day + 1;
			}
			else
			{
				tomorrowDay = 1;
				tomorrowMonth = month + 1;
			}
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			if (day < 30)
			{
				tomorrowDay = day + 1;
			}
			else
			{
				tomorrowDay  = 1;
				tomorrowMonth = month + 1;
			}
			break;
		case 12:
			if (day < 31)
			{
				tomorrowDay = day + 1;
			}
			else
			{
				tomorrowDay = 1;
				tomorrowMonth = 1;
				if (year == 2012)
				{
					printf("2012 is over.\n");
					return 0;
				}
				else
				{
					tomorrowYear = year + 1;
				}
			}
			break;
		case 2:
			if (day < 28)
			{
				tomorrowDay = day + 1;
			}
			else if(day == 28)
			{
				if(leapYear(year))
				{
					tomorrowDay = 29;
				}
				else
				{
					tomorrowDay = 1;
					tomorrowMonth = 3;						
				}
			}
			else if (day == 29)
			{
				tomorrowDay = 1;
				tomorrowMonth = 3;
			}
			else
			{
				printf("Cannot hanve Feb. %d.\n", day);
				return 0;
			}
			break;
		default:
			break;
	}
	printf("Tomorrow date is %d %d %d\n", tomorrowMonth, tomorrowDay, tomorrowYear);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值