我们最近在课堂上讨论了“if 语句等……”,但我在这个问题上遇到了麻烦。(为我糟糕的英语道歉)
这是问题:
这是我充满错误的答案:
private void button1_Click(object sender, EventArgs e)
{
//Declaring Variables
int totalSeconds;
int hours;
int minutes;
int minutesRemainder;
int hoursRemainderMinutes;
int hoursRemainderSeconds;
// Parsing and calculations
totalSeconds = int.Parse(textBox1.Text);
minutes = totalSeconds / 60;
minutesRemainder = totalSeconds % 60;
hours = minutes / 60;
hoursRemainderMinutes = minutes % 60;
hoursRemainderSeconds = hoursRemainderMinutes % 60;
if (totalSeconds >= 60)
{
MessageBox.Show(totalSeconds.ToString());
}
else if (totalSeconds >= 3600)
{
MessageBox.Show(minutes.ToString() + " minutes, " + minutesRemainder.ToString() + " seconds");
}
else if (totalSeconds >= 84600)
{
MessageBox.Show(hours.ToString() + " hours, " + hoursRemainderMinutes.ToString() + " minutes, " + hoursRemainderSeconds.ToString() + " seconds");
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
运行时,我的程序不计算任何东西。我究竟做错了什么?
您应该使用TimeSpan.FromSeconds 方法。
它将为您提供TimeSpan结构实例,您可以在其中访问:
TotalDaysTotalHoursTotalMinutes特性。
编辑
他们在评论中说你想在不使用任何库的情况下实现这一目标。那么方法是(就你的任务而言):
int totalSeconds = ....;///
int totalMinutes = totalSeconds / 60;
int totalHours = totalMinutes / 60;
int totalDays = totalHours / 24;
if (totalDays > 0){
//show days
} else if (totalHours > 0){
//show hours
} else if (totalMinutes > 0){
//show minutes
} else {
//show seconds
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3008 次 |
| 最近记录: |