首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#如何制作年龄计算器?

C#如何制作年龄计算器?
EN

Stack Overflow用户
提问于 2020-02-22 15:09:14
回答 1查看 166关注 0票数 0

我做了一个非常简单(不准确)的程序来计算你的年龄。我想通过计算闰年并考虑到每个月有不同的天数来使其准确。有帮助吗?如何做到这一点,从哪里开始?谢谢!

代码语言:javascript
复制
using System;

public class Program
{
    public static void Main()
    {
        float currentDay = 22;
        float currentMonth = 2;
        float currentYear = 2020;

        Console.WriteLine("Enter your date of birth: (eg: 13/04/1998)");
        Console.Write("Day: ");
        int dayNum = Convert.ToInt16(Console.ReadLine());
        Console.Write("Month: ");
        int monthNum = Convert.ToInt16(Console.ReadLine());
        Console.Write("Year: ");
        int yearNum = Convert.ToInt16(Console.ReadLine());

        float birthDay = (currentDay - dayNum) / 365;
        float birthMonth = (currentMonth - monthNum) / 12;
        float birthYear = currentYear - yearNum;

        float age = birthYear + birthMonth + birthDay;

        Console.WriteLine("Your age is: " + age);



    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-02-22 16:56:04

我给你的建议如下:

代码语言:javascript
复制
public static string ToAgeString(this DateTime dob)
{
    DateTime today = DateTime.Today;

    int months = today.Month - dob.Month;
    int years = today.Year - dob.Year;

    if (today.Day < dob.Day)
    {
        months--;
    }

    if (months < 0)
    {
        years--;
        months += 12;
    }

    int days = (today - dob.AddMonths((years * 12) + months)).Days;

    return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
                         years, (years == 1) ? "" : "s",
                         months, (months == 1) ? "" : "s",
                         days, (days == 1) ? "" : "s");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60349866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档