c++ - 修复日期类增量 (C++)
问题描述
我做了一个图书馆系统。但我刚刚检查了一下,我的“日期”工作不正常。
这堂课的首要任务
(1) Increment date
现在,我在递增日期遇到问题,当我将其递增到 25-30 的值时它工作正常。但是当我输入 90 时,它就搞砸了。
void increment_date(int num)
{
int day;
int month_new;
setDay(getDay()+num);
if( getDay()>Days_per_Month[getMonth()] )
{
day=getDay()-Days_per_Month[getMonth()];
setDay(day);
setMonth(getMonth()+1);
if(Days_per_Month[getMonth()]>12)
{
month_new=1;
setMonth(month_new);
setYear(getYear()+1);
}
}
cout<<"Return Date: ";
Print_Date();
}
//the code below is outside the class.
const int Date:: Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
int Date::checkDay(int testday) //returntype classname :: funcname (parameteres)
{
//static const int Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
if(testday > 0 && testday <= Days_per_Month[Month])
return testday;
if ( Month==2 && testday==29 && (Year%400==0 || (Year%4==0 && Year%100!=0)) ) //for leap year
return testday;
cout<<"Day "<<testday<<" invalid. Set to day 1."<<endl;
return 1;
}
解决方案
setDay(getDay()+num);
if( getDay()>Days_per_Month[getMonth()] )
{
day=getDay()-Days_per_Month[getMonth()];
setDay(day);
setMonth(getMonth()+1);
在上面的代码中,你将num
返回的值加上getDay()
,然后你检查是否getDay()
大于当月的天数,如果是,你尝试通过减去天数来纠正问题当前月份,然后递增月份。
到目前为止,一切都很好,但是如果getDay()
在你做减法之后仍然大于当月的天数怎么办?(例如,如果用户输入300
增量计数怎么办?)在这种情况下,您需要再次执行整个操作,并继续执行此操作,直到getDay()
小到足以成为有效的月内日期值。所以真的需要一个while
循环,而不仅仅是一个if
.
推荐阅读
- c# - 在 c# 中调用 Http Post 方法传递方法名称
- python - Python- 从表列表中执行 SQL 查询,并将结果存储在每个表名的单独文件中
- vbscript - 有没有办法使用 vbscript 显示 Windows 10 toast 通知?
- typescript - 类型{}、对象、对象打字稿之间的区别
- javascript - 如何从一个对象数组中获取值到另一个对象数组中
- javascript - 有没有办法在“允许使用麦克风弹出”(chrome最新)中获得“允许”按钮单击事件?
- html - 如何圆桌角
- javascript - 如何循环访问数组中的本地存储对象或转换 JSON 中的数据
- css - 覆盖 Css 文件
- excel - 如何摆脱某些零公式?