【问题标题】:calculating birthday based on the number of days the user input根据用户输入的天数计算生日
【发布时间】:2015-02-01 04:56:42
【问题描述】:

您好,我正在尝试使用用户输入的天数来计算一个人的生日。我对 ctime 库有点陌生,但我想出的是两个日期之间的差异来获得天数。据我所知,我确实了解 ctime;我知道 ctime 有一个内置的 struct tm,它由 min、secs、hour、day、month 和 year 组成。我尝试使用 asctime 将它们单独放置,但这使我的逻辑更加混乱。我使用 difftime 来查找日期之间的差异。像这样:

struct tm a = { 0, 0, 0, 1, 1, 91 }; /* my birthday */
struct tm b = { 0, 0, 0, 3, 11, 114 }; /* today's date */
time_t x = mktime(&a);
time_t y = mktime(&b);
if (x != (time_t)(-1) && y != (time_t)(-1))
{
    double days = difftime(y, x) / (60 * 60 * 24);
    cout << ctime(&x);
    cout << ctime(&y);
    cout << "difference = " << days << " days" << endl;
}

输出是:差异 = 8706 天

问题是用户输入 8706 天来获得我的生日或他们的生日。如果有意义,则此代码相反。你能帮我弄清楚解决问题的逻辑吗?

【问题讨论】:

    标签: c++ datetime ctime


    【解决方案1】:

    我没有得到你真正想要的,但如果你试图让用户输入天数并且你会得到他的生日,这很容易,只需写 结构 tm a = { 0, 0, 0, a, b, c}; /* 我的生日 */ 如果天数是 8706 诠释 c=8706/365; // 它应该给你的最大除数 23 你会得到剩余的 国际温度=23*365=8395; 然后你会做 剩余整数=8706-8395=311; 你继续寻找月份和日期.. 希望这是您的问题。

    【讨论】:

    • 它有点帮助,也许我没有问得更详细,但我正在寻找;假设用户输入自出生以来的天数,它应该从今天的日期输出用户的生日
    • #include #include using namespace std; void main() { int days,day,month,year; cout>天;年=天/365; int剩余=天-(年*365);月=剩余/30;剩余=剩余-(月*30);天=剩余; struct tm a = { 0, 0, 0, 3-day, 11-month, 114-year }; /* 我的生日 / struct tm b = { 0, 0, 0, 3, 11, 114 }; / 今天的日期 */ time_t x = mktime(&a); time_t y = mktime(&b); cout
    【解决方案2】:

    如果你可以使用Boost:

    #include <iostream>
    #include "boost/date_time/gregorian/gregorian.hpp"
    
    using namespace std;
    using namespace boost::gregorian;
    
    int main(){
        days d;
        cin >> d;
        date today = day_clock::local_day();
        date birth = today - d;
        date bday(today.year(), birth.month(), birth.day());
        if(bday < today) bday = date(today.year()+1, birth.month(), birth.day());
        cout << bday;
    }
    

    【讨论】:

    • 在访问 boost 库时遇到问题,我不断收到一条错误消息,说它无法开源
    • Boost 不是标准库的一部分。您必须下载它并在编译期间将其添加为包含路径(如果您使用 gcc,则为 -I 标志(大写“i”))。更多信息在这里:boost.org/doc/libs/1_57_0/more/getting_started/index.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多