您的位置:首页 > 其它

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

2016-11-13 19:28 465 查看

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: