我是一名学生,我想知道是否有人可以帮助我调试我的一个函数。对于这个程序,用户假设在 1972-2071 年之间以 mm/dd/yy 格式输入两个日期,并且该程序假设输出这两个日期之间的差异。除了计算从 1/1/72 开始的天数的函数外,我的所有函数都有效。这是我们的教授希望我们在没有额外功能的情况下做到这一点的方式。只是一个初学者版本,有很多 if else 语句和 for 循环。
int ChangeToNumber(int m, int d, int y)
{
int total=0;
if(y<=71) //if the year is between 2000-2071
{
y+=28;
for(int i=0; i<y; i++)
{
if(!LeapYear(y))
{
total+=365;
}
else
{
total+=366;
}
}
}
else //if the year is between 1972-1999
{
for(int i=72; i<y; i++)
{
if(!LeapYear(y))
{
total+=365;
}
else
{
total+=366;
}
}
}
for(int i=1; i<m; i++)
{
total+=DaysInMonth(m, y);
}
total += d;
return total;
}
最佳答案
您可以使用 std::difftime
在某些百分比上帮助您。
没有额外的功能:
http://en.cppreference.com/w/cpp/chrono/c/difftime
#include <iostream>
#include <ctime>
int main()
{
struct std::tm a = {0,0,0,24,5,104}; /* June 24, 2004 */
struct std::tm b = {0,0,0,5,6,104}; /* July 5, 2004 */
std::time_t x = std::mktime(&a);
std::time_t y = std::mktime(&b);
if ( x != (std::time_t)(-1) && y != (std::time_t)(-1) )
{
double difference = std::difftime(y, x) / (60 * 60 * 24);
std::cout << std::ctime(&x);
std::cout << std::ctime(&y);
std::cout << "difference = " << difference << " days" << std::endl;
}
return 0;
}
额外的功能:
#include "boost/date_time/gregorian/gregorian_types.hpp"
using namespace boost::gregorian;
date date1(2012, Apr, 2);
date date2(2003, Feb, 2);
long difference = (date1 - date2).days();
关于c++ - 如何找到两个日期之间的差异c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39947550/