如何修正年龄计算器中的leap年逻辑并找到年龄?

时间:2018-11-29 18:01:31

标签: c++

我必须编写一个计算年龄的程序,但我想提出to年逻辑,因为如果我19岁,那我就已经过了这19年中的the年。

    #include<iostream>
using namespace std;
int main()
{
    int age, months, years, days, minutes, seconds, hours, leapyear, y;
    cout<<"Enter your age in years::";
    cin>>age;

    days=age*365;
    cout<<"Age in days is:"<<days;

    months=age*12;
    cout<<"\nAge in months is:"<<months;

    hours=days*24;
    cout<<"\nAge in hours is:"<<hours;

    minutes=hours*60;
    cout<<"\nAge in minutes is:"<<minutes;

    seconds=minutes*60;
    cout<<"\nAge in seconds is:"<<seconds;


// How to fix leap year logic in this program i tried but failed to do so....

    return 0;
}

当前输出:

Enter your age in years::19
Age in days::6935
Age in months::228
Age in hours::166440
Age in minutes::9986400
Age in seconds::599184000

2 个答案:

答案 0 :(得分:2)

最简单的方法是让其他人来做繁重的工作并使用图书馆。 Howard Hinnant的date库使这些操作变得更容易:

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

using namespace date;

int main()
{
    int years = 19;
    auto today = year_month_day{ floor<days>(std::chrono::system_clock::now()) };
    auto birthday = year(static_cast<int>(today.year()) - years) / today.month() / today.day();
    auto age = static_cast< sys_days >( today ) - static_cast< sys_days >( birthday );
    std::cout << "you are " << age.count() << " days old\n";
    std::cout << "you are " << std::chrono::duration_cast< std::chrono::hours >( age ).count() << " hours old\n";
    std::cout << "you are " << std::chrono::duration_cast< std::chrono::minutes >(age).count() << " minutes old\n";
    std::cout << "you are " << std::chrono::duration_cast< std::chrono::seconds >(age).count() << " seconds old\n";
    return 0;
}

答案 1 :(得分:1)

由于您已经说过您不想问生日,所以最简单的方法是将int类型更改为double类型,并用每年365.25天来表示您的年龄。这样,每四年便增加了代表full年的一整天。

   #include<iostream>
using namespace std;
int main()
{
    double age, months, years, days, minutes, seconds, hours;
    int min, sec;
    cout<<"Enter your age in years::";
    cin>>age;

//Alternate option if you do not want to ask for date
//Add a quarter of a day each year, every four years it will add to 1 day

    days+=age*365.25;
    cout<<"Age in days is:"<<days;

    months=age*12;
    cout<<"\nAge in months is:"<<months;

    hours=days*24;
    cout<<"\nAge in hours is:"<<hours;

    minutes=hours*60;
// to make it an integer and not convert to scientific notation with high numbers
    min = (int)minutes;
    cout<<"\nAge in minutes is:"<<minutes;

    seconds=minutes*60;
    sec = (int)seconds;
    cout<<"\nAge in seconds is:"<<seconds;


    return 0;
}