【问题标题】:Trying to make it in c# where the user enters their age and it tells them what year they were born in试图在用户输入他们的年龄并告诉他们他们出生的年份的 c# 中制作它
【发布时间】:2021-04-30 22:43:10
【问题描述】:

这是我到目前为止的代码,我现在卡住了。

    static void Main(string[] args)
    {
        int age = 0;
        DateTime now = DateTime.Today;

        Console.WriteLine("What is your age?");
        age = Convert.ToInt32(Console.ReadLine());

    }

【问题讨论】:

  • 请详细说明是什么阻碍了您。你有什么问题?
  • 如前所述。说明您遇到的具体问题。给出一个可重现的例子,以及期望的输出。这将使人们更容易为您提供帮助。
  • 他们出生在哪一年总是模棱两可,这取决于他们今年是否过生日
  • @KeithNicholas 如果他们以毫秒为单位输入年龄...:D
  • 我认为您正在寻找int yearBorn = DateTime.Now.AddYears(-age).Year;(请注意,我们添加了他们年龄的负数,因为没有SubtractYears 方法)。但正如@KeithNicholas 所说,如果他们还没有过生日,你必须在结果中加一个。或者你可以直接说Console.WriteLine($"You were born in {yearBorn} (or {yearBorn + 1} if you haven't had your birthday yet");

标签: c# date


【解决方案1】:

一个简单的方法是创建一个字符串变量,它是一个 console.readline,将字符串转换为 int(age),然后从当前年份中减去年龄,这个等式的结果将是他们的年份出生。但是,这仍然不完美,好像您还没有过生日,但可能要休息一年。

String stringAge = Console.ReadLine();
int age = Convert.ToInt32(stringAge);
//year is 2021
int result = age-2021;

【讨论】:

  • 我 32 岁。我不是 1989 年出生的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
相关资源
最近更新 更多