问题描述
我是C#的新手并且已经从书中做过练习。练习是编写一个程序,从控制台读取我的年龄,并在十年后打印我的年龄。
I'm new to C# and have been doing an exercise from a book. The exercise is to write a program that reads my age from the console and prints my age after ten years from now.
这是我根据我写的代码到目前为止已经理解。
Here is the code I have written based on what I have understood so far.
namespace Page_108_Age
{
class Program
{
static void Main(string[] args)
{
//Gives date of birth
DateTime dob = new DateTime(1989, 10, 30, 23, 31, 00);
//Gives current age
DateTime today = DateTime.Today;
int age = today.Year -dob.Year;
if (today < dob.AddYears(age)) age--;
//age plus ten years
DateTime agePlusTen = age.AddYears(10);
Console.WriteLine(age);
Console.ReadLine();
}
}
}
我的问题是AddYears in第16行
My problem is that AddYears in line 16
[ DateTime dobPlusTen = age.AddYears(10);
]
给我以下错误...
我显然缺少一些东西,但现在确定我还需要定义AddYears,因为它在我的代码中没有突出显示为结构。
I'm obviously missing something but now sure what other then I think I need to define AddYears as it is not highlighted in my code as a struct.
注意:对于dobPlusTen的道歉,因为你们大多数人都选择这个是生日期加上十年的短期,这不是我想要的那样。 Age Plus Ten Years,我把它更改为agePlusTen。
推荐答案
你是wr ite:
DateTime dobPlusTen = age.AddYears(10);
这不响铃吗?
您的变量名为 dobPlusTen
,但您分配给它的值是不是 dob
+10。
Your variable is named dobPlusTen
, yet the value you assign to it is not dob
+ 10.
因此将其更改为
DateTime dobPlusTen = dob.AddYears(10);
你会没事的。
EDIT 根据Ross Dargan在这个答案下面的评论(我没有注意到确切的问题:练习是写一个程序,从控制台读取我的年龄并打印我的年龄后从现在开始十年。),它实际上要简单得多。
EDIT As per Ross Dargan's remark below this answer (I had failed to notice the exact question: The exercise is to write a program that reads my age from the console and prints my age after ten years from now.), it's actually much simpler.
只需
var line = Console.ReadLine();
int agePlus10 = Convert.ToInt32(line) + 10;
Console.WriteLine(agePlus10);
会做。
这篇关于定义AddYears,使用C#计算十年的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!