对于计算机科学作业,我需要计算用户使用出生日期到18岁之前的天数。
Dim dateToday As Date = Date.Today()
Dim ageNow As Integer = dateToday.Subtract(birthDate).Days
' 6750 is 365 * 18
Dim daysEighteen As Integer = 6750 - ageNow
MsgBox("You will be 18 in " & daysEighteen)
这是我目前的代码,但是经过测试,它没有提供正确的输出。
这不是整个代码,但我刚刚为这部分程序包含了必要的行。
提前致谢。
答案 0 :(得分:1)
我会使用不同的方法。为生日添加18年,然后减去今天的日期。这应该避免计算中隐含的错误(365 * 18不计算闰年)
Dim birthDate = New DateTime(1999,1,1)
Dim adultDate = birthDate.AddYears(18)
Console.WriteLine(adultDate.ToString("MM/dd/yyyy"))
Dim daysLeft = adultDate.Subtract(DateTime.Today).Days
Console.WriteLine(daysLeft)
答案 1 :(得分:0)
这是已完成的程序,带有注释。
Public Class Form
Private Sub btnEnter_Click(sender As System.Object, e As System.EventArgs) Handles btnEnter.Click
' Stores the textboxes as variables
Dim name As String = txtName.Text
Dim birthDate As Date = dtpBirthDate.Text
Dim electionDate As Date = dtpElectionDate.Text
' This is the age the user will be on the date of the election
Dim ageElection As Integer = electionDate.Subtract(birthDate).Days
' If the user is 18 or older, it outputs that they are. If they're not, it calculates how many days
' it will be until they are and displays it.
If (ageElection / 365) > 18 Then
' Outputs that the user is 18 or older
MsgBox("You are 18 or older!")
Else
' This is when the user will turn 18
Dim adultDate As Date = birthDate.AddYears(18)
' This calculates how many days it will be until the user is 18, using when they turn 18
Dim daysLeft = adultDate.Subtract(DateTime.Today).Days
' Outputs that the user is younger than 18 and outputs how many days until they're 18
MsgBox("You are younger than 18! You will be 18 in " & daysLeft)
End If
End Sub
End Class