如何找到两个日期之间的差异c ++

时间:2016-10-09 19:18:06

标签: c++

我是一名学生,我想知道是否有人可以帮助我调试我的一项功能。对于该程序,用户假设在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;
}

2 个答案:

答案 0 :(得分:3)

您可以使用//Encrypt if ((selection == 1) && (type == 1)) { Clear(); WriteLine("\nPlease enter the message you wish to encrypt(please exclude spaces from the message):\n"); StringBuilder s = new StringBuilder(ReadLine()); WriteLine("\nPlease enter your key word or phrase:\n"); string key = ReadLine(); VigenereEncryptDecrypt.VigenereEncrypt(ref s, key); if (ReadLine() == "gen-otp") { } Clear(); WriteLine("\nEncrypted message:\n{0}\n\nKey: {1}\n\nPlease press ENTER to continue:", s, key); ReadLine(); Clear(); CipherSelection(); } 来帮助您获得某些百分比。

没有额外的功能:

http://en.cppreference.com/w/cpp/chrono/c/difftime

std::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;
}

答案 1 :(得分:0)

我认为您正在寻找基本的格里高利历算法:

http://howardhinnant.github.io/date_algorithms.html

ChangeToNumber看起来很像http://howardhinnant.github.io/date_algorithms.html#days_from_civil 并且详细解释的算法比微不足道的1972-2071有更大的范围。

此日历算法链接的语法不是很好(尽管算法非常好)。在C ++中,您可以使用非常有效的算法实现非常好的语法,并使用如下库: https://howardhinnant.github.io/date/date.html

这个程序:

#include "chrono_io.h"
#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    std::cout << sys_days{2016_y/oct/9} - sys_days{2016_y/jan/1} << '\n';
}

输出:

282[86400]s

这意味着如果2016-01-01是第0天,那么2016-10-09是第282天

相关问题